c# BFS solution


  • 0
    N
    public class Solution {
        public int FindCircleNum(int[,] M)
        {
            var visited = new bool[M.GetLength(0)];
            var res = 0;
            for (var i = 0; i < M.GetLength(0); i++)
            {
                if (visited[i])
                {
                    continue;
                }
                bfs(i, M, visited);
                visited[i] = true;
                res++;
            }
    
            return res;
        }
        
        public void bfs(int n, int[,] m, bool[] visited)
        {
            var v = new bool[m.GetLength(0), m.GetLength(0)];
            var q = new Queue<int>();
            q.Enqueue(n);
    
            while (q.Count > 0)
            {
                var count = q.Count;
                for (var i = 0; i < count; i++)
                {
                    var t = q.Dequeue();
                    visited[t] = true;
    
                    for (var j = 0; j < m.GetLength(0); j++)
                    {
                        if (visited[j] || t == j || m[t, j] != 1) continue;
    
                        q.Enqueue(j);
                    }
                }
            }
        }
    }
    

Log in to reply
 

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