695. Max Area of Island

양성준·2025년 6월 9일

코딩테스트

목록 보기
80/102

문제

https://leetcode.com/problems/max-area-of-island/description/

풀이

class Solution {
    int answer = 0;
    int width = 0;
    int[] dx = {1,0,-1,0};
    int[] dy = {0,1,0,-1};
    public int maxAreaOfIsland(int[][] grid) {
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == 1) { 
                width = 0;
                DFS(grid, i, j);
                answer = Math.max(width, answer);
                }
            }
        }
        return answer;
    }

    public void DFS(int[][] grid, int x, int y) {
        width++;
        grid[x][y] = 0;
        for(int i = 0; i < 4; i ++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == 1) {
                DFS(grid, nx, ny);
            }
        }
        return;
    }
}
  • DFS로 탐색하면서 해당 섬들의 넓이를 구하고, 각 넓이의 최대값을 갱신
    • width를 전역변수로 선언해야 값이 복사가 되지 않아서 DFS를 거쳐도 온전히 유지됨
    • 섬의 첫 부분을 탐색할 때 width를 0으로 초기화
profile
백엔드 개발자

0개의 댓글