Simple C# solution by bfs


  • 1
    S
    public class Solution {
        private readonly int[,] _dic = new int[,]{{0,1}, {0,-1}, {1,0}, {-1,0}};
        
        public int NumIslands(char[,] grid) 
        {
            if(grid == null || grid.GetLength(0) == 0 || grid.GetLength(1) == 0)
                return 0;
            var m = grid.GetLength(0);
            var n = grid.GetLength(1);
            var result =0;
            for(int i = 0; i<m; i++)
                for(int j= 0; j<n; j++)
                {
                    if(grid[i,j] == '1')
                    {
                        var q = new Queue<Tuple<int, int>>();
                        q.Enqueue(new Tuple<int,int>(i,j));
                        grid[i,j] = '2';
                        while(q.Any())
                        {
                            var node = q.Dequeue();
                            for(var d=0; d<4; d++)
                            {
                                var x = node.Item1+_dic[d,0];
                                var y = node.Item2+_dic[d,1];
                                if(x>=0 && x<m && y>=0 && y<n && grid[x,y]=='1')
                                {
                                    grid[x,y]='2';
                                    q.Enqueue(new Tuple<int,int>(x,y));
                                }
                            }
                            
                        }
                        result++;
                    }
                }
            return result;
        }
    }
    

  • 0
    This post is deleted!

Log in to reply
 

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