0:00 / 0:00

Count groups of connected cities: pick an unvisited city, flood its whole province with a search, and count how many floods it takes.

▼

The problem

LeetCode 547 (Medium). There are n cities and an n × n matrix isConnected where isConnected[i][j] = 1 if cities i and j are directly connected (symmetric, isConnected[i][i] = 1). A province is a group of cities connected directly or indirectly, with no other city outside the group. Return the number of provinces.

LeetCode's examples are [[1,1,0],[1,1,0],[0,0,1]] → 2 and [[1,0,0],[0,1,0],[0,0,1]] → 3. The video walks through an illustrative six-city map instead, because it shows "through others" (0 reaches 4 only via 3) and a multi-step ride: roads 0-3, 3-4, 1-5, provinces {0, 3, 4}, {1, 5}, {2} → 3. The key-idea scene uses a second illustrative seven-city map (roads 0-2, 1-2, 2-4, 3-5) whose first province branches at 2, so the herald rides out and back twice.

def find_circle_num(isConnected):
    n = len(isConnected)
    seen = [False] * n
    def visit(i):
        seen[i] = True
        for j in range(n):
            if isConnected[i][j] and not seen[j]:
                visit(j)
    provinces = 0
    for i in range(n):
        if not seen[i]:
            visit(i)
            provinces += 1
    return provinces

Checked against a brute force (transitive closure, counting distinct reachability rows) on 20,000 random symmetric matrices (1 to 9 cities) and on both LeetCode examples. Time O(n²): each city is visited once and each visit reads its row of n cells (36 reads for the six-city map). Space O(n): seen and the recursion stack (depth 3 in the walkthrough: visit(0) → visit(3) → visit(4)). The slow way shown: search for a path for every pair (15 pairs for six cities, 4 of them linked), about n² searches of up to n² reads each, O(n⁴). Every value on screen is computed in code: provinces() (the same DFS, with its event list), pathBetween(), bruteCount() in src/realms.jsx, which re-checks provinces() against bruteCount() on 2,000 seeded random matrices at load; every scene asserts the values it shows, and src/gen_score.py re-runs the DFS for its cues.

TRY IT ON LEETCODE ▶

The solution

def find_circle_num(isConnected):
    n = len(isConnected)
    seen = [False] * n
    def visit(i):
        seen[i] = True
        for j in range(n):
            if isConnected[i][j] and not seen[j]:
                visit(j)
    provinces = 0
    for i in range(n):
        if not seen[i]:
            visit(i)
            provinces += 1
    return provinces

Transcript

Number of Provinces. You get n cities and a grid: a one in row i, column j means cities i and j share a road. A province is a group of cities linked directly or through others. Return how many provinces there are.

On this map, zero connects to three, and three to four, so zero reaches four through three: one province. One and five share a road: that's two. City two stands alone: three provinces.

The slow way checks every pair of cities: is there a path between them? That's about n squared searches, and each one can read the whole grid, so the work grows like n to the fourth.

The better idea: walk the cities in order. When a city has no banner yet, it starts a new province, so count one, and send a herald riding out from it. He follows every road he can and plants the same banner on each city he reaches: a depth-first search. Flagged cities are skipped later, so each province is counted once.

Let's run it. City zero has no banner: count one. The herald reads row zero and finds three. Row three leads back to zero, already flagged, and on to four. Row four only leads back, so he rides home. City one is new: count two, and its row finds five. City two is new: count three. Three, four and five are flagged: skip. Answer: three.

In code, keep a seen list. Visit marks a city, scans its row, and visits every connected city not yet seen. The main loop calls visit at each unseen city and adds one. Union find works too.

Every city is visited once, and each visit reads one row of n cells: O of n squared time, the size of the grid. Space is O of n, for the seen list and the call stack.

Find a city with no banner, flag everything it reaches, count the rides. That's Number of Provinces.