Can it be done without modifying the grid? My Java Solution


  • 0
    M
    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'){
                        count++;
                        markIsland(grid,i,j);
                    }
                }
            }
            return count;
        }
        
        void markIsland(char grid[][], int i, int j){
            if(i>-1 && j>-1 && i<grid.length && j<grid[0].length && grid[i][j]=='1'){
                grid[i][j]='2';
                markIsland(grid, i+1, j);
                markIsland(grid, i, j+1);
                markIsland(grid, i-1, j);
                markIsland(grid, i, j-1);
            }
        }
    }

Log in to reply
 

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