1219. 黄金矿工
Solution
思路:第一个想法是有点类似数塔dp
的感觉,但是这里的起点是随机,而且规模不大,所以可以逐个枚举起点,然后dfs
搜索即可。长时间不写,判断新点是否可行时,传入了旧的点,人麻了。
class Solution {
int ans = 0;
int[][] grids;
int[][] dir = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int m, n;
public int getMaximumGold(int[][] grid) {
m = grid.length;
n = grid[0].length;
grids = grid;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != 0) {
dfs(i, j, 0);
}
}
}
return ans;
}
void dfs(int x, int y, int gold) {
int res = grids[x][y];
ans = Math.max(ans, res + gold);
grids[x][y] = 0;
for (int i = 0; i < 4; i++) {
int newX = x + dir[i][0];
int newY = y + dir[i][1];
if (check(newX, newY)) {
dfs(newX, newY, res + gold);
}
}
grids[x][y] = res;
}
boolean check(int x, int y) {
if (x < 0 || x >= m || y < 0 || y >= n) return false;
if (grids[x][y] == 0) return false;
return true;
}
}