Number of Provinces
Master this topic with zero to advance depth.
Number of Provinces
Given an matrix isConnected where isConnected[i][j] = 1 if city and city are directly connected. Return the total number of provinces (connected components).
Examples
Level I: DFS (Component Counting)
Intuition
Treat the matrix as an adjacency list. For each city, if not visited, start a DFS to visit all cities in its province. Count the number of DFS starts.
Detailed Dry Run
City 0: unvisited. Count=1. DFS(0) visits City 1. City 1: visited. City 2: unvisited. Count=2. DFS(2).
Level III: Union-Find (Component ID)
Intuition
Standard DSU application. For every connection, perform a union. The answer is the initial city count minus successful unions.
Detailed Dry Run
3 Cities. Initial count=3. Union(0,1) -> success, count=2. Connection(0,2)=0 -> no union. Connection(1,2)=0 -> no union.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.