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.