Pattern visualizer
Number of Provinces
A province is whatever a single DFS from one city can reach, so the algorithm never has to look for the groups directly — it only has to make sure every city gets visited once. Walk the cities in order; whenever one has not been visited yet, that is proof it belongs to a group nobody has explored, so start a fresh DFS from it and count one more province. Cities 0 and 2 have no direct matrix entry but both end up in the same province, because 1 chains them together — the badge on each city is the province number it was assigned, and the side panel is the DFS stack for whichever province is currently being explored. Animated on: 6 cities with adjacency matrix rows [1,1,0,0,0,0], [1,1,1,0,0,0], [0,1,1,0,0,0], [0,0,0,1,1,0], [0,0,0,1,1,0], [0,0,0,0,0,1] (isConnected[i][j] = 1 means i and j are directly connected) — how many provinces are there?.
DFS from every unvisited city, reading the adjacency matrix row by row
Cities and direct connections, no province labels yet
6 cities and an n x n matrix where a 1 means the two cities are directly connected. 0 and 2 have no direct entry, but both connect through 1 — so a province is not just direct neighbours, it is everything reachable by chaining connections together.
1FUNCTION numProvinces(isConnected, n):2 visited <- ARRAY OF n FALSE3 count <- 04 FOR i FROM 0 TO n - 15 IF visited[i] CONTINUE6 count <- count + 17 stack <- [i]8 visited[i] <- true9 WHILE stack NOT EMPTY10 u <- REMOVE LAST FROM stack11 FOR j FROM 0 TO n - 112 IF isConnected[u][j] = 1 AND NOT visited[j]13 visited[j] <- true14 APPEND j TO stack15 RETURN count
← / → step · space play · Home restart