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.