Paint Bucket: Recolor a 4-Connected Region in a Grid
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests BFS/DFS grid traversal by spreading a new color through all 4-directionally connected cells sharing the starting cell's original color.
Problem
You are given a 2D grid of integers called canvas, where each value represents the color of that cell. Think of it like a paint-bucket tool in an image editor.
Given a starting cell (row, col) and a new_color, recolor the starting cell and every cell reachable from it through up, down, left, and right moves, as long as each cell along the way shares the same original color as the starting cell. Return the modified grid.
Two cells are considered connected only if they are directly adjacent (sharing an edge). Diagonal neighbors do not count.
Constraints
m == len(canvas),n == len(canvas[0])1 <= m, n <= 500 <= canvas[r][c] < 655360 <= row < m,0 <= col < n0 <= new_color < 65536
Notes
- Modify and return the same
canvasobject (in-place). - If the starting cell already has the value
new_color, return the grid as-is without any changes. - Negative indexing in Python wraps around silently — make sure your bounds checks handle this correctly.
Examples
Example 1
Input: paint_bucket_fill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2)
Output: [[2, 2, 2], [2, 2, 0], [2, 0, 1]]
Example 2
Input: paint_bucket_fill([[0, 0, 0], [0, 0, 0]], 0, 0, 2)
Output: [[2, 2, 2], [2, 2, 2]]
Hints
Hint 1
Before touching anything, save the starting cell's original color. Once you start repainting, you can no longer read it from the grid.
Hint 2
If the original color already equals new_color, return immediately — otherwise a BFS/DFS that uses the recolored state as its visited marker will loop forever.
Hint 3
Use the recoloring itself as your visited marker: a cell recolored to new_color no longer matches the original, so neighbors will naturally skip it. No separate visited set is needed.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
The problem is a connected-component traversal on a grid. Starting from (row, col), we want to visit every cell reachable through 4-directional moves where each cell along the path holds the same color as the starting cell. We recolor each visited cell to new_color.
We use BFS with a queue, processing cells level by level outward from the seed.
Step-by-step
- Record
original = canvas[row][col]before making any changes. - If
original == new_color, return immediately. Skipping this check causes an infinite loop: recoloring a cell still leaves it equal tooriginal, so neighbors keep re-adding it to the queue forever. - Recolor the seed cell and push it onto the queue.
- While the queue is non-empty, pop a cell, examine its four neighbors, and for each neighbor that is in bounds and still holds
original, recolor it and enqueue it.
Why this is correct
Recoloring doubles as a visited marker. The moment a cell is recolored it no longer equals original, so it will never be enqueued again. Every cell is therefore processed at most once — no separate visited set is needed.
Recolor on enqueue, not on dequeue. By recoloring the moment we push a cell, we prevent the same cell from being enqueued multiple times by different neighbors. If we waited until dequeue time, the queue could accumulate duplicate entries, doing redundant work (though the final result would still be correct).
Completeness. BFS visits every cell reachable through original-colored neighbors, which is exactly the 4-connected component. No reachable cell is skipped, and no unreachable cell is touched.
Edge cases
new_color == original: early return, grid unchanged.- 1×1 grid: the seed is recolored and the queue immediately empties — no neighbors to check.
- Cells only diagonally connected to the region are never enqueued, since we check only four cardinal directions.
- Bounds checking: always verify
0 <= nr < rows and 0 <= nc < colsbefore reading a neighbor. Python's negative-index wrapping would silently access the wrong row or column otherwise.
Complexity
Let m and n be the grid dimensions.
- Time: O(m · n). Each cell is enqueued and dequeued at most once, with four neighbor checks per dequeue.
- Space: O(m · n). The queue can hold up to O(m · n) cells in the worst case (e.g., the entire grid is one uniform region).
Tradeoff: BFS vs. recursive DFS
A recursive DFS solution is equally correct but carries a practical risk in Python: the default recursion limit is around 1,000 frames. On a 50×50 grid a snake-shaped region can require up to 2,500 recursive calls, which will crash with a RecursionError. BFS avoids this by using heap-allocated queue memory instead of the call stack, making it the safer production choice here.
Reference solution
from collections import deque
from typing import List
def paint_bucket_fill(canvas: List[List[int]], row: int, col: int, new_color: int) -> List[List[int]]:
rows, cols = len(canvas), len(canvas[0])
original = canvas[row][col]
if original == new_color:
return canvas
canvas[row][col] = new_color
queue = deque([(row, col)])
while queue:
r, c = queue.popleft()
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < rows and 0 <= nc < cols and canvas[nr][nc] == original:
canvas[nr][nc] = new_color
queue.append((nr, nc))
return canvas