题目
“””
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor,
“flood fill” the image.
To perform a “flood fill”, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel
of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same
color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
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.
“””
用过ps的人应该都熟悉一个功能,就是颜色填充;而这道题目的意思,其实就像颜色填充一样,把一个区域的oldColor用newColor代替,因此,这里就涉及到了如何识别一个区域?
洪水填充算法
洪水会向四周能够流动的地方流动,因此我们就可以模范洪水的流动方式:在某个点,对这个点的四个方向进行可流动性判断,如果是可流动的,那么就流过去,否则不流,其实就是判断这个点的四个方向上的点与当前的点是不是属于同一块区域,然后进行替换操作;当四个方向都执行完之后,就采用深度优先搜索向下一个点出发,继续之前的操作,直到所有需要被替换的区域都已经被替换成新的信息位置
注意点
由于DFS是递归运行的,所以可能会出现由于递归的深度过深导致栈爆炸,因此需要利用python中的sys
模块,进行如下设置
1 | sys.setrecursionlimit(100000) |
代码
1 | import sys |