深度优先May-11th “Flood Fill (Python3)”

Posted 迪乐阅读

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深度优先May-11th “Flood Fill (Python3)”相关的知识,希望对你有一定的参考价值。

——


 五月,总结模板的日子.

Day 11  ——   Flood Fill


图像渲染


问题描述

An  image  is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 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.
给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。
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.
在图像的正中间,(坐标(sr,sc)=(1,1)),
在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,
因为它不是在上下左右四个方向上与初始点相连的像素点。
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].




解题思路  


深度优先搜索+递归
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)”的主要内容,如果未能解决你的问题,请参考以下文章

May 11th 2017 Week 19th Thursday

LeetCode - Flood Fill

733. Flood Fill

733. Flood Fill

733. Flood Fill

[LeetCode] Flood Fill