Problem 313532 · medium · Phase 03 Linear Management & Searching

Repaint a Connected Region

matrix · breadth-first search · flood fill

A pixel image is an m x n grid image of integer colour codes. A user clicks the pixel at row r, column c and picks a colour. Repaint the clicked pixel and every pixel reachable from it through a chain of edge-adjacent (up, down, left, right) pixels that all share the clicked pixel's original colour. Modify image in place and return it.

Examples

Input:  image = [[1, 1, 0], [1, 0, 0], [0, 0, 1]], r = 0, c = 0, colour = 7
Output: [[7, 7, 0], [7, 0, 0], [0, 0, 1]]
Explanation: the three 1s in the top-left corner touch by edges; the 1 in the bottom-right does not.

Input:  image = [[2, 2], [2, 2]], r = 1, c = 1, colour = 2
Output: [[2, 2], [2, 2]]

Constraints

  • 1 <= m, n <= 300, 0 <= r < m, 0 <= c < n
  • Target: O(m * n) time.

Goals

  • Explore a region of equal colours with an explicit queue
  • Restrict movement to the four edge-adjacent neighbours
  • Guard against the no-op case that would otherwise loop forever
Starting Python…