C# Solution


  • 0
    K

    Basic idea is to to iterate through the entire grid. Everytime we see a '1', we know we are in a island (increment count). Only question is how big of an island is this? Simply recursively check all neighbours of this '1' and turn them to '0' so that we don't check it again. Return the total incremented sum.

    public class Solution {
        public int NumIslands(char[,] grid)
        {
            int count = 0;
            for(int i = 0; i < grid.GetLength(0); ++i){
                for(int j = 0; j < grid.GetLength(1); ++j){
                    if (grid[i,j] == '0')
                        continue;
                        
                    Helper(grid, i, j);
                    count++;
                }
            }
            return count;
        }
        
        public void Helper(char[,] grid, int x, int y){
            if (x < 0 || y < 0 || x >= grid.GetLength(0) || y >= grid.GetLength(1))
                return;
            
            if(grid[x,y] == '0')
                return;
            
            grid[x,y] = '0';
            
            Helper(grid, x-1, y);
            Helper(grid, x+1, y);
            Helper(grid, x, y-1);
            Helper(grid, x, y+1);
        }
    }
    

Log in to reply
 

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