LeetCode/cs/number-of-provinces.cs

36 lines
881 B
C#
Raw Normal View History

public class Solution {
private void BFS(int[][] graph, List<bool> visited, int u0) {
var q = new Queue<int>();
q.Enqueue(u0);
visited[u0] = true;
while (q.Count > 0) {
var u = q.Dequeue();
for (var v = 0; v < graph.Length; ++v) {
if (graph[u][v] == 0 || visited[v]) {
continue;
}
q.Enqueue(v);
visited[v] = true;
}
}
}
public int FindCircleNum(int[][] isConnected) {
var visited = new List<bool>(Enumerable.Repeat(false, isConnected.Length));
var count = 0;
for (var i = 0; i < isConnected.Length; ++i) {
if (visited[i]) {
continue;
}
BFS(isConnected, visited, i);
++count;
}
return count;
}
}