Number Of Island by DFS

Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

์ด๋ฒˆ ๊ฐ•์˜๋ถ€ํ„ฐ๋Š” DFS์™€ BFS๋ฅผ ์ฃผ๋กœ ๋‹ค๋ฃจ๋Š” ๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ ์ ‘๊ทผ๋ฐฉ๋ฒ•๊ณผ ํ’€์ด ๋ฐฉ๋ฒ•, ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋“ฑ์— ๋Œ€ํ•ด ์ž์„ธํžˆ ํ•™์Šตํ•ด๋ณผ ๊ฒƒ์ด๋‹ค. ์–ด๋ ต๊ฒŒ๋งŒ ์ƒ๊ฐํ–ˆ์—ˆ์ง€๋งŒ, ์ƒ๊ฐ๋ณด๋‹ค ๋‹จ์ˆœํ•˜๊ฒŒ ์žฌ๊ท€ ํ˜ธ์ถœ๋กœ ์‚ฌ๋ฐฉ์— ์žˆ๋Š” ์›์†Œ์— ๋ฐฉ๋ฌธํ•˜์—ฌ ํ•ด๊ฒฐํ–ˆ๋‹ค.

class Solution {
    int m;
    int n;
    public int numIslands(char[][] grid) {
        m = grid.length;
        n = grid[0].length;
        int count = 0;
        
        for(int i=0;i<m;i++) {
            for(int j=0;j<grid[i].length;j++) {
                if(grid[i][j] == '1') {
                    count++;
                    dfs(grid,i,j);
                }
            }
        }
        return count;
    }
    public void dfs(char[][] grid, int i, int j) {
        if(i<0||i>=m||j<0||j>=n||grid[i][j] != '1') return 0;
        grid[i][j] = 'X';
        
        dfs(grid,i-1,j);
        dfs(grid,i+1,j);
        dfs(grid,i,j-1);
        dfs(grid,i,j+1);
    }
}

Last updated