My Java Easy Understand Solution Using DFS


  • 0
    I
    public int numIslands(char[][] grid) {
        if (grid.length==0){
            return 0;
        }
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        int result = 0;
        for (int i = 0; i<grid.length;i++){
            for (int j = 0; j<grid[0].length;j++){
                if (grid[i][j]=='1'&&!visited[i][j]){
                    if (helperDFS(grid, visited, i,j)){
                        result++;
                    }
                }
            }
        }
        return result;
    }
    public boolean helperDFS(char[][] grid, boolean[][] visited, int i, int j){
        if (i>=0&&i<grid.length&&j>=0&&j<grid[0].length&&grid[i][j]=='1'&&!visited[i][j]){
             visited[i][j] = true;
             helperDFS(grid, visited, i+1,j); 
             helperDFS(grid, visited, i-1,j); 
             helperDFS(grid, visited, i,j+1);
             helperDFS(grid, visited, i,j-1);
            return true;
        }
       
        return false;
    }

Log in to reply
 

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