Number of Islands
LeetCode 200 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Count DFS launches from unvisited land.
நான் Number of Islands (LeetCode 200) ஐ இப்படித் தீர்த்தேன் — Graph Fundamentals / BFS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Each island is a connected group of '1' cells. Scan the grid; every unvisited land cell starts a new island, and a DFS marks all of its connected land as visited.
Approach
- 1
Visited set.
- 2
For each '1' not yet visited: DFS, count++.
- 3
DFS marks the cell and recurses into land neighbours.
நான் எப்படித் தீர்த்தேன்
Grid DFSPythonO(m·n) time
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""
Simple DFS
"""
visited = set()
components = 0
m = len(grid)
n = len(grid[0])
def dfs(row,col):
visited.add((row,col))
di = [0,+1,0,-1]
dj = [+1,0,-1,0]
for k in range(4):
nrow = row+di[k]
ncol = col+dj[k]
if 0<=nrow<m and 0<=ncol<n and (nrow,ncol) not in visited and grid[nrow][ncol]=="1":
dfs(nrow,ncol)
for row in range(m):
for col in range(n):
if grid[row][col]=="1" and (row,col) not in visited:
dfs(row,col)
components+=1
return components
Number of Islands — அடிக்கடி கேட்கப்படும் கேள்விகள்
Number of Islands பின்னாலுள்ள intuition என்ன?
Each island is a connected group of '1' cells. Scan the grid; every unvisited land cell starts a new island, and a DFS marks all of its connected land as visited.
Number of Islands (LeetCode 200) ஐ எப்படித் தீர்ப்பது?
1. Visited set. 2. For each '1' not yet visited: DFS, count++. 3. DFS marks the cell and recurses into land neighbours.
Number of Islands இன் time மற்றும் space complexity என்ன?
Time: O(m · n). Space: O(m · n). (Accepted approach: Grid DFS.)
Number of Islands இல் பொதுவான தவறுகள் என்ன?
Deep recursion on huge grids — BFS or marking the grid in place avoids it.