AC Java in-place Simple Solution


  • 0
    K
    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(countIslands(grid, i, j)) count++;
                }
            }
            return count;
        }
        
        private boolean countIslands(char[][] grid, int row, int col) {
            if(row<0 || col <0 || row >= grid.length || col >= grid[0].length || grid[row][col] == '0') return false;
            // change the char from 1 to 0 to note that it is visited.
            grid[row][col] = '0';
            // traverse in all four directions
            countIslands(grid, row, col+1);
            countIslands(grid, row, col-1);
            countIslands(grid, row+1, col);
            countIslands(grid, row-1, col);
            return true;
        }
    }
    

Log in to reply
 

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