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 47 48
| public class Solution {
int ans = -1; int[][] directions = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int EscapeFromCave (int[][] cave, int hp) { int x = 0, y = 0; for (int i = 0; i < cave.length; i++) { for (int j = 0; j < cave[0].length; j++) if (cave[i][j] == -2) { x = i; y = j; break; } if ( x != 0 && y != 0) break; } boolean[][] visited = new boolean[cave.length][cave[0].length]; visited[x][y] = true; dfs(cave, x, y, hp, visited); return ans; }
public void dfs(int[][] cave, int curi, int curj, int hp, boolean[][] visited) { if (hp <= 0) return ; if (cave[curi][curj] == -3) { ans = Math.max(ans, hp - 3); return ; }
for (int[] dir : directions) { int tempi = curi + dir[0], tempj = curj + dir[1]; if (tempi < 0 || tempi >= cave.length || tempj < 0 || tempj >= cave[0].length || cave[tempi][tempj] == -1 || visited[tempi][tempj]) continue; visited[tempi][tempj] = true; dfs(cave, tempi, tempj, hp - cave[tempi][tempj], visited); } } }
|