Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Flood Fill

LeetCode #733Easy
Recolour a connected region

Given an image grid, a starting pixel, and a new color, repaint that pixel and every pixel reachable from it through 4-directionally adjacent pixels of the same original color, then return the modified image.

Asked atAmazonGoogle
step 1 / 32
3 × 3 image · new colour 2
1
1
1
1
1
0
1
0
1
Recursive DFS flood
1oldColor = image[sr][sc]
2if oldColor == newColor: return image
3dfs(r, c):
4 image[r][c] = newColor
5 if out of bounds: return
6 if image[nr][nc] != oldColor: skip
7 dfs(nr, nc) // each of 4 neighbours
8dfs(sr, sc); return image
state
  • start(1, 1)
  • oldColor1
  • newColor2

line 1Flood Fill is the "paint bucket" tool. We start at (1, 1), note its colour (1), and recolour every cell connected to it through up/down/left/right moves that ALSO has that original colour — repainting them to 2. Different colours and the grid edge are the walls that stop the spread.