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.