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
| private boolean[] test = new boolean[2]; private boolean[][] used; private List<List<Integer>> result = new ArrayList<>(); private int[][] move = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public List<List<Integer>> pacificAtlantic(int[][] heights) { for (int i = 0; i < heights.length; i++) { for (int j = 0; j < heights[0].length; j++) { used = new boolean[heights.length][heights[0].length]; test[0] = false; test[1] = false; dfs(heights, i, j); if (test[0] && test[1]) result.add(List.of(i, j)); } } return result; } private void dfs(int[][] heights, int y, int x) { if (test[0] && test[1]) return; if (x < 0 || x >= heights[0].length || y < 0 || y >= heights.length || used[y][x]) return; used[y][x] = true; if (x == 0 || y == 0) test[0] = true; if (x == heights[0].length - 1 || y == heights.length - 1) test[1] = true; if (y + 1 < heights.length && heights[y][x] >= heights[y + 1][x]) dfs(heights, y + 1, x); if (y - 1 >= 0 && heights[y][x] >= heights[y - 1][x]) dfs(heights, y - 1, x); if (x + 1 < heights[0].length && heights[y][x] >= heights[y][x + 1]) dfs(heights, y, x + 1); if (x - 1 >= 0 && heights[y][x] >= heights[y][x - 1]) dfs(heights, y, x - 1); }
|