From 5dded1796b6dd13cff1a844eff0c33b6a8962a77 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 7 Jan 2024 21:15:19 +0100 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=E2=80=9C547.=20Number=20of=20Provi?= =?UTF-8?q?nces=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/number-of-provinces.cs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 cs/number-of-provinces.cs diff --git a/cs/number-of-provinces.cs b/cs/number-of-provinces.cs new file mode 100644 index 0000000..6795cd8 --- /dev/null +++ b/cs/number-of-provinces.cs @@ -0,0 +1,35 @@ +public class Solution { + private void BFS(int[][] graph, List visited, int u0) { + var q = new Queue(); + 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(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; + } +}