1. 题目
2. 思路
(1) DFS+回溯法
- 从每一个有黄金的格子开始向上下左右四个方向进行深度优先搜索,若不能向四周搜索时,则比较当前格子累计的黄金是否大于最大黄金数。
- 每探索一个格子,将该格子的值置为相反数,标记该格子已经被搜索过,回溯时恢复该格子的值。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int[][] grid;
public int m;
public int n;
public int res;
public int getMaximumGold(int[][] grid) {
this.grid = grid;
m = grid.length;
n = grid[0].length;
res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != 0) {
dfs(i, j, 0);
}
}
}
return res;
}
public void dfs(int i, int j, int sum) {
boolean move = false;
sum += grid[i][j];
grid[i][j] = -grid[i][j];
if (i > 0 && grid[i - 1][j] > 0) {
dfs(i - 1, j, sum);
move = true;
}
if (i < m - 1 && grid[i + 1][j] > 0) {
dfs(i + 1, j, sum);
move = true;
}
if (j > 0 && grid[i][j - 1] > 0) {
dfs(i, j - 1, sum);
move = true;
}
if (j < n - 1 && grid[i][j + 1] > 0) {
dfs(i, j + 1, sum);
move = true;
}
grid[i][j] = -grid[i][j];
if (!move) {
res = Math.max(res, sum);
}
}
}