JAVA DFS solution


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

Log in to reply
 

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