Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color.
Example1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
Note:
The length of image and image[0] will be in the range [1, 50].
The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
The value of each color in image[i][j] and newColor will be an integer in [0, 65535].
Solutions
Solution 1: DFS
Thinking
The 4-connected component of \((sr,sc)\) must be recolored. A full-image scan would recolor disconnected cells of the same color.
Only cells reachable from the start with color \(oc\) matter, which DFS visits.
Return on out-of-range, a color other than \(oc\), or the new color already; otherwise paint and recurse to four neighbors. The new-color test also stops infinite recursion when \(oc\) equals \(newColor\).
We design a function \(dfs(i, j)\) to start filling color from \((i, j)\). If \((i, j)\) is not within the image range, or the color of \((i, j)\) is not the original color, or the color of \((i, j)\) has been filled with the new color, then return. Otherwise, fill the color of \((i, j)\) with the new color, and then recursively search the four directions: up, down, left, and right of \((i, j)\).
The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\). Where \(m\) and \(n\) are the number of rows and columns in the image, respectively.
DFS uses the call stack, which can be \(mn\) deep on a long snake.
BFS expands the same four-neighborhood from a queue, with equivalent marks and no deep recursion.
We can use the method of breadth-first search. Starting from the initial point, fill the color of the initial point with the new color, and then add the initial point to the queue. Each time a point is taken from the queue, the points in the four directions: up, down, left, and right are added to the queue, until the queue is empty.
The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\). Where \(m\) and \(n\) are the number of rows and columns in the image, respectively.