Flood Fill
LeetCode 733 · Easy · solution, intuition & step-by-step walkthrough
DFS through cells of the starting colour.
This is how I solved Flood Fill (LeetCode 733), an easy problem from the Graph Fundamentals / DFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a 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.
How I solved it
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 — FAQ
What is the intuition behind Flood Fill?
Starting from (sr, sc), recolour every cell connected to it that has the original colour. A DFS spreads through same-coloured neighbours.
How do you solve Flood Fill (LeetCode 733)?
1. Remember the starting colour. 2. DFS: paint the cell, recurse into same-coloured unvisited neighbours.
What is the time and space complexity of Flood Fill?
Time: O(m · n). Space: O(m · n). (Accepted approach: Grid DFS.)
What are common mistakes in Flood Fill?
If the new colour equals the old one, a visited set (or early return) prevents infinite loops.