3ms AC solution using dfs, in Java


  • 3
    G
    public class Solution {
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
        int result = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '0') continue;
                dfs(grid, i, j);
                result++;
            }
        }
        return result;
    }
    
    private void dfs(char[][] grid, int x, int y) {
        grid[x][y] = '0';
        if (x > 0 && grid[x - 1][y] == '1') dfs(grid, x - 1, y);
        if (x < grid.length - 1 && grid[x + 1][y] == '1') dfs(grid, x + 1, y);
        if (y > 0 && grid[x][y - 1] == '1') dfs(grid, x, y - 1);
        if (y < grid[x].length - 1 && grid[x][y + 1] == '1') dfs(grid, x, y + 1);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.