Flood Fill
LeetCode 733 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
DFS through cells of the starting colour.
நான் Flood Fill (LeetCode 733) ஐ இப்படித் தீர்த்தேன் — Graph Fundamentals / DFS பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Starting from (sr, sc), recolour every cell connected to it that has the original colour. A DFS spreads through same-coloured neighbours.
Approach
- 1
Remember the starting colour.
- 2
DFS: paint the cell, recurse into same-coloured unvisited neighbours.
நான் எப்படித் தீர்த்தேன்
Grid DFSPythonO(m·n) time
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
m = len(image)
n = len(image[0])
di = [0,+1,0,-1]
dj = [+1,0,-1,0]
default_color = image[sr][sc]
visited = set()
visited.add((sr,sc))
def dfs(row,col):
visited.add((row,col))
image[row][col]=color
for k in range(4):
nrow = row+di[k]
ncol = col+dj[k]
if 0<=nrow<m and 0<=ncol<n and image[nrow][ncol]==default_color and (nrow,ncol) not in visited:
dfs(nrow,ncol)
dfs(sr,sc)
return image
Flood Fill — அடிக்கடி கேட்கப்படும் கேள்விகள்
Flood Fill பின்னாலுள்ள intuition என்ன?
Starting from (sr, sc), recolour every cell connected to it that has the original colour. A DFS spreads through same-coloured neighbours.
Flood Fill (LeetCode 733) ஐ எப்படித் தீர்ப்பது?
1. Remember the starting colour. 2. DFS: paint the cell, recurse into same-coloured unvisited neighbours.
Flood Fill இன் time மற்றும் space complexity என்ன?
Time: O(m · n). Space: O(m · n). (Accepted approach: Grid DFS.)
Flood Fill இல் பொதுவான தவறுகள் என்ன?
If the new colour equals the old one, a visited set (or early return) prevents infinite loops.