题目搬运者
https://leetcode-cn.com/problems/flood-fill/
一幅图像用m × n的整数网格图像表示,其中image[i][j]表示图像的像素值。
你也被给予三个整数sr, sc和newColor。你应该从像素image[sr][sc]开始对图像进行填充。
为了执行泛洪填充,考虑起始像素,加上任意4方向上连接到与起始像素相同颜色的起始像素的像素,再加上任意4方向上连接到这些像素(同样具有相同的颜色)的像素,以此类推。用newColor替换上述所有像素的颜色
思路 广度优先算法
- 首先要有四个维度的方向坐标 [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
- 要有一个依次入队的队列
- 先push入原坐标,在push原坐标周围相同像素的四个点,并给坐标像素上色
- 在依次从queue中pop出队头坐标,在坐标周围相同像素的四个点进行判断和push操作,给坐标像素上色
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
oldColor = image[sr][sc]
if oldColor == newColor: return image
n = len(image)
m = len(image[0])
que = collections.deque([(sr, sc)])
image[sr][sc] = newColor
while que:
x, y = que.popleft()
for mx, my in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
if 0 <= mx < n and 0 <= my < m and image[mx][my] == oldColor:
que.append((mx, my))
image[mx][my] = newColor
return image
关于python队列的学习
https://blog.youkuaiyun.com/chl183/article/details/106958004
collections模块 ==> Python标准库,数据结构常用的模块;collections包含了一些特殊的容器,针对Python内置的容器,例如list、dict、set和tuple,提供了另一种选择。
deque()
deque是栈和队列的一种广义实现,deque是"double-end queue"的简称;deque支持线程安全、有效内存地以近似O(1)的性能在deque的两端插入和删除元素,尽管list也支持相似的操作,但是它主要在固定长度操作上的优化,从而在pop(0)和insert(0,v)(会改变数据的位置和大小)上有O(n)的时间复杂度。
deque()
- append()
- appendleft()
- extend()
- extendleft()
- pop()
- popleft()
- count()
- insert(index,obj)
- rotate(n)
- clear()
- remove()
- maxlen()
#双边队列
dq = deque(['a','b'])
#增加数据到队尾
dq.append('c')
#增加数据到队左
dq.appendleft('d')
# 从右端逐个添加可迭代对象(与list同)
ex = (1, "h", 3)
st = "abcd"
list1 = [0, 1, 2, 3]
dst = deque(st)
dlist1 = deque(list1)
dlist1 = extend(ex)
# deque([0, 1, 2, 3, 1, 'h', 3])
dst.extendleft(ex)
# deque([3, 'h', 1, 'a', 'b', 'c', 'd'])
#输出队列所有数据
print(dq)
#移除队尾,并返回
print(dq.pop())
#移除队左,并返回
print(dq.popleft())#输出:deque(['d', 'a', 'b', 'c'])cd