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#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

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

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.