Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 547 · Graph Fundamentals / DFS + DSU

Number of Provinces

LeetCode 547 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Count connected components with DFS.

நடுத்தரம்Depth-First SearchBreadth-First SearchUnion-FindGraph Theory
LeetCode இல் திற ↗

நான் 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. 1

    For each unvisited city, DFS and count a province.

  2. 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.