KatInterview

Paint Bucket: Recolor a 4-Connected Region in a Grid

Trees & GraphsAuto-graded · 21 test cases
EasyAuto-gradedTrees & Graphsbfsgridgraph-traversal

Last 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 <= 50
  • 0 <= canvas[r][c] < 65536
  • 0 <= row < m, 0 <= col < n
  • 0 <= new_color < 65536

Notes

  • Modify and return the same canvas object (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.