VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 11: Graphs

Lesson 11.8 of 16 in this module Unrolled Pro

Number of Provinces

Count the groups of cities connected directly or indirectly, given an adjacency matrix. From computing the full transitive closure (every pair reachable from every other, O(n³)), to one DFS or BFS per unvisited city (O(n²) on a matrix, O(V + E) on lists), to union-find over the edges. Then connections that arrive over time, the size of each group, sparse inputs given as edge lists, and the ML use: clustering entities that are linked by 'same as' signals.

about 10 min 3 Python examples 2 quick checks

Problem. There are n cities. is_connected[i][j] = 1 if cities i and j are directly connected. A province is a group of cities connected directly or through other cities, with no city outside the group connected to any inside. Return the number of provinces.

text
is_connected = [[1, 1, 0],
                [1, 1, 0],          →   2      ({0, 1} and {2})
                [0, 0, 1]]

It's lesson 11.3's connected components, on a general graph given as an adjacency matrix instead of a grid. The matrix is the input's shape, and it sets the cost: reading it is already O(n²).

ML context. Clustering by links: user accounts linked by shared devices, product listings linked by "same item" predictions, papers linked by citations, entity mentions linked by a coreference model. The clusters are the connected components of the "same as" graph. Links usually arrive over time from a model or from logs, which is where union-find shines (Change A and lesson 11.15).


1. Step 1: Clarify

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Number of Provinces"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee