1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| public class one_two_one_nine_黄金矿工 {
@Test public void test(){ int[][] grid = {{0,6,0}, {5,8,7}, {0,9,0}}; int result = getMaximumGold(grid); System.out.println(result); }
private int res = 0;
public int getMaximumGold(int[][] grid) { for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { backtrace(grid, i, j, 0); } } return res; }
public void backtrace(int[][] grid, int x, int y, int money){ if (!check(grid, x, y)) return ; if (grid[x][y] == 0){ res = Math.max(res, money); return ; } int stored = grid[x][y]; money += stored; grid[x][y] = 0; backtrace(grid, x - 1, y, money); backtrace(grid, x, y - 1, money); backtrace(grid, x + 1, y, money); backtrace(grid, x, y + 1, money); money -= stored; grid[x][y] = stored; }
public boolean check(int[][] grid, int x, int y){ return (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length ); } }
|