An image is stored as an m × n grid of whole numbers called image, where each number is the colour of one pixel. You are also given a starting pixel (sr, sc) and a new colour color.
Repaint the region that contains the starting pixel: every pixel that has the starting pixel's original colour and can be reached from it by stepping up, down, left or right through pixels of that same colour. Diagonal steps do not count. Every pixel in the region gets color.
Return the image after the repaint.
Example 1
Input: image = [[5,5,1,5],[1,5,5,1],[5,1,5,1]], sr = 1, sc = 1, color = 7 Output: [[7,7,1,5],[1,7,7,1],[5,1,7,1]] Why: five 5s link to (1, 1) by sides; the 5s at (0, 3) and (2, 0) do not
2 more examples and the constraints
Example 2
Input: image = [[4,4],[4,4]], sr = 0, sc = 1, color = 4 Output: [[4,4],[4,4]] Why: the region is already colour 4, so nothing changes
Example 3
Input: image = [[2,0,2],[0,2,0]], sr = 0, sc = 0, color = 6 Output: [[6,0,2],[0,2,0]] Why: the other 2s touch (0, 0) only at a corner, which does not count
Constraints
- The image has between 1 and 50 rows and between 1 and 50 columns
- Every pixel value and
colorare at least 0 and below 65,536 - The start pixel
(sr, sc)lies inside the image
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursive DFSO(m·n)
- BFS with a queueO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 50 × 50 image | Verdict |
|---|---|---|---|
| Recursive DFS | O(m·n) | Short; mind the stack depth | |
| BFS with a queue | O(m·n) | Best; no recursion limit |
m = rows, n = columns.
Edge cases to test
- New colour equals the old one. Return at once. Without that check, the recursion never stops because painted cells still look unpainted.
- Diagonal neighbours. A same-coloured pixel that only touches the region at a corner keeps its colour.
- One pixel. [[3]] with color 8 becomes [[8]].
- Whole image one colour. Every pixel changes; a 50 × 50 image is 2,500 cells deep for plain recursion.
Common mistakes
- Skipping the
old == colorcheck, so the fill loops forever. - Reading the start colour after painting the start pixel, so
oldis already the new colour. - Spreading to diagonal neighbours, or forgetting the bounds check on the last row or column.
How to talk through it
- 1Clarify. Do diagonals count? Can the new colour equal the old one? Can I change the image in place?
- 2Name the pattern. This is a connected-region search on a grid: DFS or BFS from the start pixel.
- 3Handle the trap first. If
color == old, return right away, before any painting. - 4Code the spread. Paint as you visit or queue, so painting doubles as the visited mark.
- 5Test out loud. Run the same-colour case, a corner-touching pixel and a single-pixel image.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?