Number of provinces
Count the connected components of an undirected graph: groups of cities linked directly or indirectly.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Scan every node. Whenever you find one that has not been visited, it belongs to a province nobody has counted yet: count it, then DFS (or BFS) outward to mark every node reachable from it, so the same province is never counted twice.
Code
public static int CountProvinces(Dictionary<char, List<char>> graph) {
var seen = new HashSet<char>();
int count = 0;
foreach (char u in graph.Keys)
if (seen.Add(u)) { count++; Visit(u, graph, seen); }
return count;
}
static void Visit(char u, Dictionary<char, List<char>> graph, HashSet<char> seen) {
foreach (char v in graph[u])
if (seen.Add(v)) Visit(v, graph, seen);
}static int countProvinces(Map<Character, List<Character>> graph) {
Set<Character> seen = new HashSet<>();
int count = 0;
for (char u : graph.keySet())
if (seen.add(u)) { count++; visit(u, graph, seen); }
return count;
}
static void visit(char u, Map<Character, List<Character>> graph, Set<Character> seen) {
for (char v : graph.get(u))
if (seen.add(v)) visit(v, graph, seen);
}void visit(char u, unordered_map<char, vector<char>>& graph, unordered_set<char>& seen) {
for (char v : graph[u])
if (seen.insert(v).second) visit(v, graph, seen);
}
int countProvinces(unordered_map<char, vector<char>>& graph) {
unordered_set<char> seen;
int count = 0;
for (auto& [u, _] : graph)
if (seen.insert(u).second) { count++; visit(u, graph, seen); }
return count;
}def count_provinces(graph: dict[str, list[str]]) -> int:
seen: set[str] = set()
count = 0
for u in graph:
if u not in seen: seen.add(u); count += 1; visit(u, graph, seen)
return count
def visit(u: str, graph: dict[str, list[str]], seen: set[str]) -> None:
for v in graph[u]:
if v not in seen: seen.add(v); visit(v, graph, seen)Tips
- LeetCode phrases this with an isConnected adjacency matrix, but the moment you build the adjacency list from it, it is the exact same component count.
- Union-find solves this too: the final number of distinct roots is the number of provinces.
In the .NET library
This pattern, "scan for an unvisited node, flood fill, count", is the same shape as counting islands in a grid; a grid is just a graph where each cell links to its four neighbours.