Graph Theory37 sections · 1633 units
Open in Course

LeetCode 547 Number of Provinces - Input

Adjacency Matrix Trap

LeetCode gives you isConnected, which is an adjacency matrix. isConnected[i][j] = 1 means there is an edge between cities ii and jj. You need to convert this to DFS logic.

Instead of building an adjacency list, you can DFS directly on the matrix. When exploring neighbors of city uu, loop through all cities vv from 00 to n1n-1. If isConnected[u][v] = 1 and vv is not visited, recurse on vv. This works fine for small nn (up to a few hundred). For large graphs, adjacency lists are faster.