Number of Provinces
LeetCode 547 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Count connected components with DFS.
मैंने Number of Provinces (LeetCode 547) ऐसे हल किया — Graph Fundamentals / DFS + DSU पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Cities and direct connections form a graph given as an adjacency matrix. Each DFS from an unvisited city marks one connected component — one province.
Approach
- 1
For each unvisited city, DFS and count a province.
- 2
DFS visits every city with isConnected[u][v] == 1.
मैंने कैसे हल किया
DFS on adjacency matrixPythonO(n²) time
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
n = len(isConnected)
visited = set()
def dfs(u):
visited.add(u)
for v in range(n):
if isConnected[u][v]==1 and v not in visited:
dfs(v)
components=0
for u in range(n):
if u not in visited:
dfs(u)
components+=1
return components
Number of Provinces — अक्सर पूछे जाने वाले प्रश्न
Number of Provinces के पीछे intuition क्या है?
Cities and direct connections form a graph given as an adjacency matrix. Each DFS from an unvisited city marks one connected component — one province.
Number of Provinces (LeetCode 547) कैसे हल करें?
1. For each unvisited city, DFS and count a province. 2. DFS visits every city with isConnected[u][v] == 1.
Number of Provinces की time और space complexity क्या है?
Time: O(n²)। Space: O(n)। (Accepted approach: DFS on adjacency matrix।)
Number of Provinces में आम गलतियाँ क्या हैं?
The matrix is symmetric — no need to look at both triangles specially.