In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:
- Every time you are located in a cell you will collect all the gold in that cell.
- From your position, you can walk one step to the left, right, up, or down.
- You can't visit the same cell more than once.
- Never visit a cell with
0gold. - You can start and stop collecting gold from any position in the grid that has some gold.
Example 1:
Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
[5,8,7],
[0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.
Example 2:
Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
[2,0,6],
[3,4,5],
[0,3,0],
[9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 150 <= grid[i][j] <= 100- There are at most 25 cells containing gold.
题意:你要开发一座金矿,地质勘测学家已经探明了这座金矿中的资源分布,并用大小为 m * n 的网格 grid 进行了标注。每个单元格中的整数就表示这一单元格中的黄金数量;如果该单元格是空的,那么就是 0。
为了使收益最大化,矿工需要按以下规则来开采黄金:
- 每当矿工进入一个单元,就会收集该单元格中的所有黄金。
- 矿工每次可以从当前位置向上下左右四个方向走。
- 每个单元格只能被开采(进入)一次。
- 不得开采(进入)黄金数目为
0的单元格。 - 矿工可以从网格中 任意一个 有黄金的单元格出发或者是停止。
解法 DFS
简单题:
class Solution {
private:
int n, m;
int dfs(vector<vector<int>>& g, int x, int y) {
if (x < 0 || x >= n || y < 0 || y >= m || !g[x][y]) return 0;
int v = g[x][y];
g[x][y] = 0;
int ans = v + max(dfs(g, x - 1, y), max(dfs(g, x + 1, y), max(dfs(g, x, y - 1), dfs(g, x, y + 1))));
g[x][y] = v; //恢复现场
return ans;
}
public:
int getMaximumGold(vector<vector<int>>& grid) {
n = grid.size(), m = grid[0].size();
int ans = 0;
for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) if (grid[i][j]) ans = max(ans, dfs(grid, i, j));
return ans;
}
};
运行效率如下:
执行用时:48 ms, 在所有 C++ 提交中击败了92.54% 的用户
内存消耗:7.1 MB, 在所有 C++ 提交中击败了83.33% 的用户

这篇博客讨论了一种解决策略,即通过深度优先搜索(DFS)算法来确定在给定的金矿网格中获取最多黄金的路径。题目描述了一个包含黄金的网格,矿工可以按上下左右移动,但不能重复访问同一单元格或访问含有0黄金的单元格。提供的C++代码实现了DFS算法,能够在限定时间内找到最优解,表现出良好的时间和空间效率。
1817

被折叠的 条评论
为什么被折叠?



