200. Number of Islands

JJ·2021년 1월 6일
0

Algorithms

목록 보기
52/114
class Solution {
    char[][] count;
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        int count = 0;
        int h = grid.length;
        int w = grid[0].length;
        
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    helper(grid, i, j);
                }
            }
        }
        
        return count;
    }
    
    public void helper(char[][] grid, int x, int y) {
        if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == '0') {
            return;
        }
        grid[x][y] = '0';
        helper(grid, x - 1, y);
        helper(grid, x + 1, y);
        helper(grid, x, y - 1);
        helper(grid, x, y + 1);
    }
}

Runtime: 1 ms, faster than 99.99% of Java online submissions for Number of Islands.
Memory Usage: 41.7 MB, less than 40.66% of Java online submissions for Number of Islands.

내 사랑? DFS를 또 써봤읍니다
언제 BFS와도 친해져야 할텐데..

0개의 댓글