广度优先遍历算法:与深度优先遍历算法比较来看,拿深度优先算法那个例子来说就是:先查4个地方的机票价格再查各个地方的酒店价格,一层一层的查。 1.
def bfs(numcourses, prelist):
prelistcount = [0] * numcourses
for line in prelist:
for i in range(len(line)):
if line[i] == 1:
prelistcount[i] += 1
cantake = []
for i in range(len(prelistcount)):
if prelistcount == 0:
cantake.append(i)
classtake = []
while len(cantake) != 0:
thisclass = cantake[0]
del cantake[0]
classtake.append(thisclass)
for i in range(numcourses):
if prelist[thisclass][i] == 1:
prelistcount[i] -= 1
if prelistcount[i] == 0:
cantake.append(i)
return classtake
def bfs(set, m, n, matrix):
dir = [[0, 1], [0, -1], [1, 0], [-1, 0]]
queue = list(set)
while len(queue) > 0:
x, y = queue.pop()
for d in dir:
nx = x + d[0]
ny = y + d[1]
if 0 <= nx and nx < m and 0 <= ny and ny < n:
if matrix[nx][ny] >= matrix[x][y]:
if (nx, ny) not in set:
queue.append((nx, ny))
set.add((nx, ny))
return set
def solve(matrix):
if not matrix:
return matrix
m = len(matrix)
n = len(matrix[0])
toppoint = set([(0, y) for y in range(n)])
leftpoint = set([(x, 0) for x in range(m)])
bottompoint = set([(m - 1, y) for y in range(n)])
rightpoint = set([(x, n - 1) for x in range(m)])
bfs(toppoint, m, n, matrix)
bfs(leftpoint, m, n, matrix)
bfs(bottompoint, m, n, matrix)
bfs(rightpoint, m, n, matrix)
result = toppoint & leftpoint & bottompoint & rightpoint
return result
matrix = [[1, 3, 2, 3, 5],
[3, 4, 5, 6, 3],
[2, 7, 4, 3, 3],
[5, 2, 2, 3, 1]]
s = solve(matrix)
print(s)
3.在一个给定的输入字符串中,移除掉最少量的错误的括号,从而使的这个字符串变为有效的字符串,并且返回所有有效的字符串
def isvalid(str):
count = 0
for c in str:
if c == '(':
count += 1
elif c == ')':
count -= 1
if count < 0:
return False
return count == 0
def bfs(str):
res = []
queue = [str]
while len(queue) > 0:
for i in range(len(queue)):
if isvalid(queue[i]):
res.append(queue[i])
if len(res) > 0:
return list(set(res))
temp = []
for s in queue:
for i in range(len(s)):
if s[i] == '(' or s[i] == ')':
temp.append(s[:i] + s[i + 1:])
queue = list(set(temp))
return list(set(res))
4.给定一个二叉树,想想你自己站在该二叉树的右侧,去采摘最外层树上的柠檬
class treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def rightside(root):
result = []
queue = [root]
while len(queue) > 0:
length = len(queue)
for i in range(length):
node = queue.pop()
if i == length - 1:
result.append(node.val)
if node.left != None:
queue.append(node.left)
if node.right != None:
queue.append(node.right)
return result
node1 = treenode(1)
node2 = treenode(2)
node3 = treenode(3)
node1.right = node2
node2.right = node3
print(rightside(node1))
|