时间:2020-7-26
题目地址:https://leetcode-cn.com/problems/flood-fill/
题目难度:Easy
题目描述:
有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。
给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。
为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。
最后返回经过上色渲染后的图像。
示例 1:
输入:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
输出: [[2,2,2],[2,2,0],[2,0,1]]
解析:
在图像的正中间,(坐标(sr,sc)=(1,1)),
在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,
因为它不是在上下左右四个方向上与初始点相连的像素点。
注意:
image 和 image[0] 的长度在范围 [1, 50] 内。
给出的初始点将满足 0 <= sr < image.length 和 0 <= sc < image[0].length。
image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535]内。
思路1:广度优先遍历,辅助列表
之前做岛屿数量的时候看过大神 四个方向偏移量 的技巧
读题倒是很快,解题倒是有思路,一共花了3h?现在简单题也做不动了?
代码段1:通过
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
m = len(image)
n = len(image[0])
marked = [[False for _ in range(n)] for _ in range(m)]
temp = [(sr, sc)]
target = image[sr][sc]
# marked[sr][sc] = True
# image[sr][sc] = newColor
for pixel in temp:
cur_x, cur_y = pixel
image[cur_x][cur_y] = newColor
print((cur_x,cur_y))
for direction in directions:
new_i = cur_x + direction[0]
new_j = cur_y + direction[1]
if 0 <= new_i < m and 0 <= new_j < n and image[new_i][new_j] == target and (new_i, new_j) not in temp:
temp.append((new_i, new_j))
print(temp)
if not marked[new_i][new_j]:
image[new_i][new_j] = newColor
marked[new_i][new_j] = True
print("%s " %marked)
return image
总结:
- 自己写的逻辑还是冗余,怪不得写了好长时间
- 内存100%,还可以,继续加油
-
在 Python 中,可以使用以下几种方法实现队列
第一种:collections包里的deque,对应操作
pop()从尾取出
appendleft() 从头插入
第二种:queue包中的queue,对应操作
put() 插入
get() 取出
第三种:直接使用list,只要保证只使用
pop() 取出
insert(0,) 插入
或者只使用
append() 插入
list[0]并且del list[0] 取出
两者使用list方法的不同就区别于你把哪个当头,哪个当尾
三种方法各有优劣。第一种是正统的Python的双端队列,缺点是调用的函数有点复杂,可能一不小心写了append,就不对了。
第二种使用封装的函数很直接,put()和get()不容易搞混淆。但是queue类型其实里面本身就装了一个deque,有点脱裤子放X的感觉。
第三种优势在于不用调包,但是函数使用逻辑可能造成混淆。在
这里,完整版代码采用第二种,好理解,精简版代码采用第三种,省行数。三种方式可以按照你的喜好互相替换,完全不影响结果。
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
if newColor == image[sr][sc]:
return image
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
m = len(image)
n = len(image[0])
temp = [(sr, sc)]
target = image[sr][sc]
for pixel in temp:
cur_x, cur_y = pixel
image[cur_x][cur_y] = newColor
for direction in directions:
new_i = cur_x + direction[0]
new_j = cur_y + direction[1]
if 0 <= new_i < m and 0 <= new_j < n and image[new_i][new_j] == target:
temp.append((new_i, new_j))
return image
本文深入讲解了图像填充算法,特别是广度优先搜索(BFS)和深度优先搜索(DFS)两种方法的应用。通过实例演示了如何从指定起点开始,将与起始点颜色相同的相邻像素替换为新颜色,详细解释了算法的实现步骤和代码细节。
291

被折叠的 条评论
为什么被折叠?



