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.