Repaint a Connected Patch of Tiles

Implement paintRegion

You are given a grid of tile colours and a starting tile. Repaint the starting tile and every tile connected to it through same-coloured tiles (moving up, down, left or right) with a new colour, and return the grid.

The trap: when the new colour equals the old one, no work is needed. A search that recognises unpainted tiles by their colour would otherwise keep revisiting tiles.

Example 1:

Input: image = [[3,3,5],[3,5,5],[7,3,3]], sr = 1, sc = 0, color = 9

Output: [[9,9,5],[9,5,5],[7,3,3]]

Example 2:

Input: image = [[4,4],[4,4]], sr = 0, sc = 1, color = 4

Output: [[4,4],[4,4]]

Example 3:

Input: image = [[1,2,1]], sr = 0, sc = 0, color = 6

Output: [[6,2,1]]

+ 13 hidden test cases run on Submit.

Constraints:

  • ●1 ≤ rows, cols ≤ 12; 0 ≤ image[r][c], color ≤ 99
  • ●0 ≤ sr < rows and 0 ≤ sc < cols give the starting tile
  • ●A patch is every tile reachable from the start by moving up, down, left or right through tiles of the same colour as the start
  • ●Repaint the whole patch with color and return the new grid (the input grid must not be needed afterwards)

image =

[[3,3,5], [3,5,5], [7,3,3]]

sr =

1

sc =

0

color =

9