Skip to content
BytePatterns

Repaint A Connected Region

EasyMatrix & Grid#flood-fill#dfs~15m

Problem

A grid of numbers represents the colours of an image. Given a starting cell and a new colour, repaint the starting cell and every cell reachable from it by steps up, down, left or right that pass only through cells of the starting cell's original colour. Return the grid.

Examples

Input:  grid = [[1, 1, 1],
                [1, 1, 0],
                [1, 0, 1]], row = 1, col = 1, colour = 2
Output: [[2, 2, 2],
         [2, 2, 0],
         [2, 0, 1]]
Why:    the bottom-right 1 only touches the region diagonally, so it stays
Input:  grid = [[5]], row = 0, col = 0, colour = 3
Output: [[3]]
Input:  grid = [[0, 0],
                [0, 0]], row = 0, col = 0, colour = 0
Output: [[0, 0],
         [0, 0]]
Why:    edge case, repainting with the same colour changes nothing

Hints

0 / 3

Stuck on the idea rather than the code? Flood Fill covers it.