深度优先May-11th “Flood Fill (Python3)”
Posted 迪乐阅读
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深度优先May-11th “Flood Fill (Python3)”相关的知识,希望对你有一定的参考价值。
——
image
is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
(sr, sc)
representing the starting pixel (row and column) of the flood fill, and a pixel value
newColor
, "flood fill" the image.
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.在图像的正中间,(坐标(sr,sc)=(1,1)), 在路径上所有符合条件的像素点的颜色都被更改成2。 注意,右下角的像素没有更改为2, 因为它不是在上下左右四个方向上与初始点相连的像素点。
The length of
image
andimage[0]
will be in the range[1, 50]
.The given starting pixel will satisfy
0 <= sr < image.length
and0 <= sc < image[0].length
.The value of each color in
image[i][j]
andnewColor
will be an integer in[0, 65535]
.
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
R, C = len(image), len(image[0])
color = image[sr][sc]
if color == newColor: return image
def dfs(r, c):
if image[r][c] == color:
image[r][c] = newColor
if r >= 1: dfs(r-1, c)
if r+1 < R: dfs(r+1, c)
if c >= 1: dfs(r, c-1)
if c+1 < C: dfs(r, c+1)
dfs(sr, sc)
return image
时间复杂度:O(N)。
空间复杂度:O(N)。
以上是关于深度优先May-11th “Flood Fill (Python3)”的主要内容,如果未能解决你的问题,请参考以下文章