My simple Java Solution:)


  • 0
    S
    public class Solution {
        int numOfRow;
        int numOfCol;
        
        public int numIslands(char[][] grid) {
            int numOfIsland = 0;
            numOfRow = grid.length;
            if(numOfRow == 0)  return 0;
            numOfCol = grid[0].length;
            
            for(int i=0; i<numOfRow; i++) {
                for(int j=0; j<numOfCol; j++){
                    if(grid[i][j] == '1') {
                        numOfIsland++;
                        dfs(grid, i, j);
                    }
                }
            }
            
            return numOfIsland;
        }
        
        public void dfs(char[][] grid, int i, int j) {
           if(i< 0 || i >= numOfRow || j < 0 || j >= numOfCol || grid[i][j] != '1') return;
           grid[i][j] = '0'; //if we can change the grid...
           dfs(grid, i-1, j);
           dfs(grid, i, j-1);
           dfs(grid, i, j+1);
           dfs(grid, i+1, j);
        }
        
    }

Log in to reply
 

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