|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +class Solution { |
| 5 | + private static int R |
| 6 | + private static int C; |
| 7 | + private static int[][] land; |
| 8 | + private static int[][] idAtPoint; |
| 9 | + private static boolean[][] visited; |
| 10 | + private static int[] dr = {1, -1, 0, 0}; |
| 11 | + private static int[] dc = {0, 0, 1, -1}; |
| 12 | + private static List<Integer> countAtId; |
| 13 | + |
| 14 | + public int solution(int[][] lland) { |
| 15 | + land = lland; |
| 16 | + R = land.length; |
| 17 | + C = land[0].length; |
| 18 | + visited = new boolean[R][C]; |
| 19 | + idAtPoint = new int[R][C]; |
| 20 | + countAtId = new ArrayList<>(); |
| 21 | + countAtId.add(0);//0생략 |
| 22 | + int id = 1; |
| 23 | + for(int r=0; r<R; r++){ |
| 24 | + for(int c=0; c<C; c++){ |
| 25 | + if(land[r][c] == 1 && !visited[r][c]){ |
| 26 | + bfs(r, c, id++); |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + int answer = 0; |
| 32 | + for(int c=0; c<C; c++){ |
| 33 | + int oilAtCol = 0; |
| 34 | + var passedId = new HashSet<Integer>(); |
| 35 | + for(int r=0; r<R; r++){ |
| 36 | + if(land[r][c] == 0) continue; |
| 37 | + int IdAtP = idAtPoint[r][c]; |
| 38 | + if(passedId.contains(IdAtP)) continue; |
| 39 | + passedId.add(IdAtP); |
| 40 | + oilAtCol += countAtId.get(IdAtP); |
| 41 | + } |
| 42 | + answer = Math.max(answer, oilAtCol); |
| 43 | + } |
| 44 | + return answer; |
| 45 | + } |
| 46 | + |
| 47 | + private void bfs(int sr, int sc, int id){ |
| 48 | + var q = new ArrayDeque<int[]>(); |
| 49 | + q.add(new int[]{sr, sc}); |
| 50 | + visited[sr][sc] = true; |
| 51 | + idAtPoint[sr][sc] = id; |
| 52 | + |
| 53 | + int temp = 0; |
| 54 | + while(!q.isEmpty()){ |
| 55 | + int[] cur = q.poll(); |
| 56 | + int r = cur[0] |
| 57 | + int c = cur[1]; |
| 58 | + temp++; |
| 59 | + for(int d=0; d<4; d++){ |
| 60 | + int nr = r + dr[d]; |
| 61 | + int nc = c + dc[d]; |
| 62 | + if(nr<0 || nr>=R || nc<0 || nc>=C) continue; |
| 63 | + if(visited[nr][nc]) continue; |
| 64 | + if(land[nr][nc] == 0) continue; |
| 65 | + visited[nr][nc] = true; |
| 66 | + idAtPoint[nr][nc] = id; |
| 67 | + q.add(new int[]{nr, nc}); |
| 68 | + } |
| 69 | + } |
| 70 | + countAtId.add(temp); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +``` |
0 commit comments