Number of provinces

Count the connected components of an undirected graph: groups of cities linked directly or indirectly.

Time O(V + E)Space O(V)Code C#, Java, C++ and Python
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

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.