Surrounded Regions
LeetCode 130 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Mark border-connected O's, flip the rest.
நான் Surrounded Regions (LeetCode 130) ஐ இப்படித் தீர்த்தேன் — Graph Fundamentals / DFS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
An 'O' survives only if it's connected to the border. Flood from every border 'O' to mark the safe ones; every unmarked 'O' is surrounded and flips to 'X'.
Approach
- 1
DFS from each 'O' on the four borders.
- 2
Mark visited cells.
- 3
Flip every unvisited 'O' to 'X'.
நான் எப்படித் தீர்த்தேன்
Border DFSPythonO(m·n) time
class Solution:
def solve(self, board: list[list[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0])
visited = [[False]*n for _ in range(m)]
di = [0,+1,0,-1]
dj = [+1,0,-1,0]
def dfs(row,col):
visited[row][col]=True
for k in range(4):
nrow = row+di[k]
ncol = col+dj[k]
if 0<=nrow<m and 0<=ncol<n and visited[nrow][ncol]==False and board[nrow][ncol]=="O":
dfs(nrow,ncol)
for j in range(n):
#first row
if board[0][j]=="O":
dfs(0,j)
#last row
if board[m-1][j]=="O":
dfs(m-1,j)
for i in range(m):
#first column
if board[i][0]=="O":
dfs(i,0)
#last column
if board[i][n-1]=="O":
dfs(i,n-1)
for row in range(m):
for col in range(n):
if visited[row][col]==False and board[row][col]=="O":
board[row][col]="X" Surrounded Regions — அடிக்கடி கேட்கப்படும் கேள்விகள்
Surrounded Regions பின்னாலுள்ள intuition என்ன?
An 'O' survives only if it's connected to the border. Flood from every border 'O' to mark the safe ones; every unmarked 'O' is surrounded and flips to 'X'.
Surrounded Regions (LeetCode 130) ஐ எப்படித் தீர்ப்பது?
1. DFS from each 'O' on the four borders. 2. Mark visited cells. 3. Flip every unvisited 'O' to 'X'.
Surrounded Regions இன் time மற்றும் space complexity என்ன?
Time: O(m · n). Space: O(m · n). (Accepted approach: Border DFS.)
Surrounded Regions இல் பொதுவான தவறுகள் என்ன?
Searching from interior O's is much harder — start from the border.