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 同步地址:
https://github.com/grandyang/leetcode/issues/1219
參考資料:
https://leetcode.com/problems/path-with-maximum-gold/