Repaint Connected Tiles

Easy · Graphs, BFS & DFS · about 15 min

A floor-design app stores a floor as a grid of tiles. Each tile holds a colour number. The bucket tool works like this: you pick a starting tile (row, col) and a new color. The starting tile and every tile you can reach from it by stepping up, down, left or right through tiles of the same original colour as the starting tile get the new colour. Diagonal steps do not count.

Return the grid after the bucket tool runs. You may change the grid you are given. If color is already the starting tile's colour, the grid stays the same.

  • The grid has at least one row and one column. row and col are inside it.

Example:

repaint_tiles([[1, 1, 0], [1, 0, 0], [1, 1, 1]], 0, 0, 2) → [[2, 2, 0], [2, 0, 0], [2, 2, 2]]

Hints

  • Save the starting tile's colour before you change anything.
  • If the new colour equals the saved colour, return the grid straight away.
  • Keep a stack of tiles to visit. Paint a tile when you push it, and only push neighbours inside the grid that still have the saved colour.

Learn the pattern first: the Graphs, BFS & DFS lesson.

More Graphs, BFS & DFS problems