Simple/Easy to Understand Java Solution [3ms]


  • 0
    T

    We just need to iterate through the char double array to find any instance of '1'. Once that is found, we floodfill at that point, essentially turning that point and any surrounding ones to '0'. Afterwards, we continue looping until we reach the end.

    public class Solution {
        public int numIslands(char[][] grid) {
            if (grid.length == 0) {
                return 0;
            }
            
            int num = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[i].length; j++) {
                    char c = grid[i][j];
                    
                    if (c == '1') {
                        num++;
                        floodfill(grid, i, j);
                    }
                }
            }
            
            return num;
        }
        
        public void floodfill(char[][] grid, int i, int j) {
            if (i >= grid.length || j >= grid[0].length 
                || i < 0 || j < 0) {
                return;
            }
            
            if (grid[i][j] == '1') {
                grid[i][j] = '0';
                floodfill(grid, i+1, j);
                floodfill(grid, i-1, j);
                floodfill(grid, i, j+1);
                floodfill(grid, i, j-1);
            }
        }
    }
    

Log in to reply
 

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