LeetCode/cs/number-of-provinces.cs
Matej Focko 5dded1796b
cs: add “547. Number of Provinces”
Signed-off-by: Matej Focko <mfocko@redhat.com>
2024-01-07 21:15:19 +01:00

35 lines
881 B
C#

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;
}
}