Leetcode中的Queue & Stack部分学习总结
Stack部分:733. Flood fill
以下代码可以作为DFS的新范式进行参考,代码较为简洁(毕竟头条写DFS模板时候被喷冗余的那一幕仍然历历在目= =)。
class Solution():
def floodFill(self, image, sr, sc, newColor):
if len(image) == 0:
return image
elif image[sr][sc] == newColor:
return image
self.fill(image, sr, sc, newColor, image[sr][sc])
return image
def fill(self, image, sr, sc, newColor, color):
# 进入递归之前,先判断传入坐标合不合法,否则直接返回。
if (sr < 0) or (sr > len(image) - 1) or (sc < 0) or (sc > len(image[0]) - 1) or (image[sr][sc] != color):
return
image[sr][sc] = newColor
self.fill(image, sr-1, sc, newColor, color)
self.fill(image, sc+1, sc, newColor, color)
self.fill(image, sc, sr-1, newColor, color)
self.fill(image, sc, sr+1, newColor, color)
return
Queue部分:752. Open The Lock
以下题目作为BFS的范式进行参考,BTW,BFS的题目貌似做的比较少,应该要多多练习才行。
# 这里使用了Python原生collections中的dequeue类,也是双端队列高效的实现。
import collections
class Solution(object):
def openLock(self, deadends, target):
if target is None or target in deadends:
return -1
# Storing all deadends in a hash table
deadends, visited, level = set(deadends), set(), 0
queue = collections.deque()
# Breath first search for the target
queue.append("0000")
while(len(queue) != 0):
currSize, level = len(queue), level + 1
for i in range(currSize):
node = queue.popleft()
# Early stop
if node in deadends or node in visited:
continue
# Current node possible adjacent nodes
possibleLocks = []
for i in range(4):
possibleLocks.append(node[:i] + str((int(node[i]) + 1) % 10) + node[(i+1):] )
possibleLocks.append(node[:i] + str((int(node[i]) + 9) % 10) + node[(i+1):] )
# Travsel the possible nodes
for j in possibleLocks:
if j == target:
return level
elif j not in deadends and j not in visited:
queue.append(j)
visited.add(node)
return -1
待续...
原文地址:https://www.cnblogs.com/GradientBoosted/p/11328387.html
时间: 2024-11-14 12:54:31