Description
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
0
gold. - 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.length
n == grid[i].length
1 <= m, n <= 15
0 <= grid[i][j] <= 100
- There are at most 25 cells containing gold.
这道题给了一个 m by n 的二维数组 grid,说是里面的数字代表金子的数量,0表示没有金子。现在可以选一个任意的起点,可以朝四个方向走,条件的是不能越界,不能走重复的位置,以及不能走值为0的地方,现在问最多能获得多少的金子。这道题虽然说也是一道迷宫遍历的问题,也是求极值的问题,但并不是求最短步数,而是求路径值之和最大,那么显然 BFS 就不太适合了,因为这里严格限制了不能走重复路径,并且要统计每一条路径之和,用 DFS 是坠好的。这道题的时间卡的非常的严格,博主最开始写的一个版本,由于用了 HashSet 来记录访问过的位置,都超时了,于是只能用 grid 数组本身来记录,首先遍历所有的位置,跳过所有为0的位置,对于有金子的位置,调用递归函数。
为了节省时间,这里的递归函数都加上了返回值,博主一般是不喜欢加返回值的。在递归函数中,首先判断当前位置是否越界,且是否有金子,不满足的话直接返回0。然后此时记录当前位置的金子数到一个变量 val 中,然后将当前位置的值置为0,表示访问过了,然后对其四个邻居位置调用递归函数,将最大值取出来放到变量 mx 中,之后将当前位置恢复为 val 值,并返回 mx+val 即可。用所有非0位置为起点调用递归函数的返回值中取最大值就是所求结果,参见代码如下:
class Solution { public: int getMaximumGold(vector<vector<int>>& grid) { int res = 0, m = grid.size(), n = grid[0].size(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == 0) continue; res = max(res, helper(grid, i, j)); } } return res; } int helper(vector<vector<int>>& grid, int i, int j) { int m = grid.size(), n = grid[0].size(); if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) return 0; int val = grid[i][j], mx = 0; grid[i][j] = 0; mx = max({helper(grid, i + 1, j), helper(grid, i - 1, j), helper(grid, i, j + 1), helper(grid, i, j - 1)}); grid[i][j] = val; return mx + val; } };
Github 同步地址:
参考资料: