My simple C# BFS solution


  • 0
    S
    public class Solution {
        private readonly int[,] dic = new int[,]{{0,1}, {0,-1}, {1,0}, {-1,0}};
        
        public int NumIslands(char[,] grid) 
        {
            var result =0;
            if(grid == null || grid.GetLength(0) == 0 || grid.GetLength(1) == 0)
                return result;
            for(int i=0; i<grid.GetLength(0); i++)
            {
                for(int j=0; j<grid.GetLength(1); j++)
                {
                    if(grid[i,j]!='1')
                        continue;
                    result++;
                    Bfs(grid,i,j);
                }
            }
            return result;
        }
        
        private void Bfs(char[,] grid, int i, int j)
        {
            grid[i,j] = '2';
            var queue = new Queue<Tuple<int,int>>();
            queue.Enqueue(new Tuple<int,int>(i,j));
            while(queue.Count>0)
            {
                var node = queue.Dequeue();
                for(int k = 0; k<4; k++)
                {
                    var m = node.Item1+dic[k,0];
                    var n = node.Item2+dic[k,1];
                    if(m>=0 && m<grid.GetLength(0) && n>=0 && n<grid.GetLength(1) && grid[m,n]=='1')
                    {
                        grid[m,n] = '2';
                        queue.Enqueue(new Tuple<int,int>(m,n));
                    }
                }
            }
        }
    }
    

Log in to reply
 

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