리트코드 - 695. Max Area of Island

홍성진·2023년 3월 10일
0

리트코드 - 695. Max Area of Island

0과 1로 이루어진 2-d array grid가 주어집니다. grid에서 가로 세로로 연결된 1들의 group을 island라고 할 때, 제일 큰 island의 면적을 구하는 문제입니다.

값이 1인 좌표만 queue에 넣고 bfs를 실시합니다. queue에서 값을 꺼낼 때마다 depth를 늘려 면적을 갱신했습니다.

import java.util.*;

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        Queue<int[]> queue = new LinkedList<>();
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        int[] dx = new int[] {1, -1, 0, 0};
        int[] dy = new int[] {0, 0, 1, -1};
        int[] cur = new int[2];
        int maxi = 0;
        int depth;
        int x;
        int y;

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] != 0 && visited[i][j] == false) {
                    queue.add(new int[] {i, j});
                    depth = 0;
                    while (!queue.isEmpty()) {
                        cur = queue.poll();
                        x = cur[0];
                        y = cur[1];

                        if (visited[x][y] == true) {
                            continue;
                        }

                        visited[x][y] = true;
                        depth++;
                        maxi = Math.max(maxi, depth);

                        for (int k = 0; k < 4; k++) {
                            int nx = x + dx[k];
                            int ny = y + dy[k];

                            if (nx >= 0 && nx < grid.length
                                    && ny >= 0 && ny < grid[0].length
                                            && grid[nx][ny] != 0) {

                                queue.add(new int[] {nx, ny});
                            }
                        }
                    }
                }
            }
        }

        return maxi;
    }
}

0개의 댓글