|
| 1 | +/** |
| 2 | + BFS를 통해, 방문 지점이 겹치는 부분을 찾는 방식 |
| 3 | + */ |
| 4 | +class Solution { |
| 5 | + public static int[] moveX = {0, 1, 0, -1}; |
| 6 | + public static int[] moveY = {1, 0, -1, 0}; |
| 7 | + public boolean[][] POvisited; |
| 8 | + public boolean[][] AOvisited; |
| 9 | + public int N; |
| 10 | + public int M; |
| 11 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 12 | + List<List<Integer>> result = new ArrayList<>(); |
| 13 | + N = heights.length; |
| 14 | + M = heights[0].length; |
| 15 | + POvisited = new boolean[N][M]; |
| 16 | + AOvisited = new boolean[N][M]; |
| 17 | + Queue<int[]> que = new LinkedList<>(); |
| 18 | + Queue<int[]> que2 = new LinkedList<>(); |
| 19 | + |
| 20 | + for(int i = 0; i < M; i++) { |
| 21 | + POvisited[0][i] = true; |
| 22 | + que.add(new int[]{0, i}); |
| 23 | + AOvisited[N-1][i] = true; |
| 24 | + que2.add(new int[]{N-1, i}); |
| 25 | + } |
| 26 | + |
| 27 | + for(int i = 0; i < N; i++) { |
| 28 | + POvisited[i][0] = true; |
| 29 | + que.add(new int[]{i, 0}); |
| 30 | + AOvisited[i][M-1] = true; |
| 31 | + que2.add(new int[]{i, M-1}); |
| 32 | + } |
| 33 | + bfs(que, POvisited, heights); |
| 34 | + bfs(que2, AOvisited, heights); |
| 35 | + |
| 36 | + for(int i = 0; i < N; i++) { |
| 37 | + for(int j = 0; j < M; j++) { |
| 38 | + if(POvisited[i][j] && AOvisited[i][j]) { |
| 39 | + result.add(new ArrayList<>(List.of(i, j))); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return result; |
| 45 | + } |
| 46 | + |
| 47 | + public void bfs(Queue<int[]> que, boolean[][] visited, int[][] heights) { |
| 48 | + while(!que.isEmpty()) { |
| 49 | + int[] node = que.poll(); |
| 50 | + for(int i = 0; i < 4; i++) { |
| 51 | + int tempX = node[0] + moveX[i]; |
| 52 | + int tempY = node[1] + moveY[i]; |
| 53 | + if(isOutOfIndex(tempX, tempY)) { |
| 54 | + continue; |
| 55 | + } |
| 56 | + |
| 57 | + if(visited[tempX][tempY]) { |
| 58 | + continue; |
| 59 | + } |
| 60 | + if(heights[tempX][tempY] < heights[node[0]][node[1]]) { |
| 61 | + continue; |
| 62 | + } |
| 63 | + |
| 64 | + visited[tempX][tempY] = true; |
| 65 | + que.add(new int[]{tempX, tempY}); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + public boolean isOutOfIndex(int x, int y){ |
| 71 | + return x < 0 || x >= N || y < 0 || y >= M; |
| 72 | + } |
| 73 | +} |
0 commit comments