LeetCode 题解工作台
黄金矿工
你要开发一座金矿,地质勘测学家已经探明了这座金矿中的资源分布,并用大小为 m * n 的网格 grid 进行了标注。每个单元格中的整数就表示这一单元格中的黄金数量;如果该单元格是空的,那么就是 0 。 为了使收益最大化,矿工需要按以下规则来开采黄金: 每当矿工进入一个单元,就会收集该单元格中的所有黄…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 回溯·pruning
答案摘要
我们可以枚举每个格子作为起点,然后从起点开始进行深度优先搜索。在搜索的过程中,每遇到一个非零的格子,就将其变成零,并继续搜索。当无法继续搜索时,计算当前的路径的黄金总数,然后将当前的格子变回非零的格子,从而进行回溯。 时间复杂度 $O(m \times n \times 3^k)$,其中 是每条路径的最大长度。由于每个格子最多只能被访问一次,因此时间复杂度不会超过 $O(m \times n \…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路
题目描述
你要开发一座金矿,地质勘测学家已经探明了这座金矿中的资源分布,并用大小为 m * n 的网格 grid 进行了标注。每个单元格中的整数就表示这一单元格中的黄金数量;如果该单元格是空的,那么就是 0。
为了使收益最大化,矿工需要按以下规则来开采黄金:
- 每当矿工进入一个单元,就会收集该单元格中的所有黄金。
- 矿工每次可以从当前位置向上下左右四个方向走。
- 每个单元格只能被开采(进入)一次。
- 不得开采(进入)黄金数目为
0的单元格。 - 矿工可以从网格中 任意一个 有黄金的单元格出发或者是停止。
示例 1:
输入:grid = [[0,6,0],[5,8,7],[0,9,0]] 输出:24 解释: [[0,6,0], [5,8,7], [0,9,0]] 一种收集最多黄金的路线是:9 -> 8 -> 7。
示例 2:
输入:grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]] 输出:28 解释: [[1,0,7], [2,0,6], [3,4,5], [0,3,0], [9,0,20]] 一种收集最多黄金的路线是:1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7。
提示:
1 <= grid.length, grid[i].length <= 150 <= grid[i][j] <= 100- 最多 25 个单元格中有黄金。
解题思路
方法一:DFS
我们可以枚举每个格子作为起点,然后从起点开始进行深度优先搜索。在搜索的过程中,每遇到一个非零的格子,就将其变成零,并继续搜索。当无法继续搜索时,计算当前的路径的黄金总数,然后将当前的格子变回非零的格子,从而进行回溯。
时间复杂度 ,其中 是每条路径的最大长度。由于每个格子最多只能被访问一次,因此时间复杂度不会超过 。空间复杂度 。
class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
def dfs(i: int, j: int) -> int:
if not (0 <= i < m and 0 <= j < n and grid[i][j]):
return 0
v = grid[i][j]
grid[i][j] = 0
ans = max(dfs(i + a, j + b) for a, b in pairwise(dirs)) + v
grid[i][j] = v
return ans
m, n = len(grid), len(grid[0])
dirs = (-1, 0, 1, 0, -1)
return max(dfs(i, j) for i in range(m) for j in range(n))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(m \cdot n - g + g \cdot 3^g) |
| 空间 | O(g \cdot 3^g) |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates clear understanding of backtracking and pruning techniques.
- question_mark
The solution shows efficient handling of recursion and exploration within the problem's constraints.
- question_mark
The candidate applies memoization and pruning to reduce redundant calculations effectively.
常见陷阱
外企场景- error
Failing to correctly handle the grid boundaries, which can lead to out-of-bounds errors.
- error
Not properly pruning unpromising paths, leading to inefficient and slower solutions.
- error
Overcomplicating the problem with unnecessary data structures instead of focusing on the core recursive solution.
进阶变体
外企场景- arrow_right_alt
Grid size increases (beyond 15x15), requiring a more optimized approach.
- arrow_right_alt
Different traversal constraints (e.g., limiting movement to certain directions).
- arrow_right_alt
Alternative ways to handle the grid representation, such as using a dynamic programming approach.