Number of Enclaves
LeetCode 1020 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Flood from the border, count the rest.
நான் Number of Enclaves (LeetCode 1020) ஐ இப்படித் தீர்த்தேன் — Graph Fundamentals / DFS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Land connected to the border can walk off the grid. DFS from every border land cell to mark it; any land left unmarked is enclosed.
Approach
- 1
DFS from every land cell on the four borders.
- 2
Count land cells not visited.
நான் எப்படித் தீர்த்தேன்
Border DFSPythonO(m·n) time
class Solution:
def numEnclaves(self, board: List[List[int]]) -> int:
m = len(board)
n = len(board[0])
visited = [[False]*n for _ in range(m)]
def dfs(i,j):
visited[i][j]=True
di = [0,+1,0,-1]
dj = [+1,0,-1,0]
for k in range(4):
nrow = i+di[k]
ncol = j+dj[k]
if 0<=nrow<m and 0<=ncol<n and visited[nrow][ncol]==False and board[nrow][ncol]==1:
dfs(nrow,ncol)
for j in range(n):
#first row
if board[0][j]==1:
dfs(0,j)
#last row
if board[m-1][j]==1:
dfs(m-1,j)
for i in range(m):
#first col
if board[i][0]==1:
dfs(i,0)
#last col
if board[i][n-1]==1:
dfs(i,n-1)
count = 0
for i in range(m):
for j in range(n):
if visited[i][j]==False and board[i][j]==1:
count+=1
return countNumber of Enclaves — அடிக்கடி கேட்கப்படும் கேள்விகள்
Number of Enclaves பின்னாலுள்ள intuition என்ன?
Land connected to the border can walk off the grid. DFS from every border land cell to mark it; any land left unmarked is enclosed.
Number of Enclaves (LeetCode 1020) ஐ எப்படித் தீர்ப்பது?
1. DFS from every land cell on the four borders. 2. Count land cells not visited.
Number of Enclaves இன் time மற்றும் space complexity என்ன?
Time: O(m · n). Space: O(m · n). (Accepted approach: Border DFS.)
Number of Enclaves இல் பொதுவான தவறுகள் என்ன?
Think in reverse — find what escapes, not what's trapped.