mark 1 to 0 if visited


  • 0
    D

    public class Solution {
    public int numIslands(char[][] grid) {
    int count =0;
    for(int i=0;i<grid.length;i++){
    for(int j = 0;j<grid[0].length;j++){
    if(grid[i][j] == '1'){
    grid = fillIsland(grid,i,j);
    count++;
    }
    }
    }
    return count;
    }
    public char[][] fillIsland(char[][] grid,int row,int column){
    grid[row][column] = '0';
    if(row-1>=0 && column>=0 && grid[row-1][column] == '1'){
    grid = fillIsland(grid,row-1,column);
    }
    if(row+1<=grid[0].length && column>=0 && grid[row+1][column] == '1'){
    grid = fillIsland(grid,row+1,column);
    }
    if(row>=0 && column-1>=0 && grid[row][column-1] == '1'){
    grid = fillIsland(grid,row,column-1);
    }
    if(row>=0 && column+1<=grid.length && grid[row][column+1] == '1'){
    grid = fillIsland(grid,row,column+1);
    }
    return grid;
    }

    }


Log in to reply
 

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