回顾了运筹课写的图搜索作业,并重新编程实现了一下。
1. 广度优先搜索
1.1 题目描述
Use Breath-first search and Depth-first search to search graph below. Illustrate each execution step.
1.2 题解
- For G = (V;E) and a source vertex s, it systematically explores the edges of G to discover every vertex that is reachable from s
- Breadth-first search expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier
- color[u]:
- white (undiscovered),
- gray (discovered but not scanned)
- black (discovered and scanned)
① V={s,u,v,w,x,y,z}
② Adjacency-list:
③
1.3 编程实现
数据准备
def primalData():
graph = {
's': ['v', 'x'],
'u': ['v', 'x', 'y', 'z'],
'v': ['s', 'u', 'w'],
'w': ['v'],
'x': ['s', 'u', 'y'],
'y': ['u', 'x', 'z'],
'z': ['u', 'y']
}
return graph
from collections import deque
class Search():
def __init__(self, graph, start_point):
self.graph = graph
self.start_point = start_point
def BFS(self):
res = [] # 储存搜索结果
queue = deque(self.start_point) # 广度优先搜索的辅助队列,用collections.deque实现
visited_set = set() # 储存访问过的点集合,防止重复访问
while queue:
n = len(queue)
temp = [] # 放这一层的元素
for _ in range(n):
cur = queue.popleft()
temp.append(cur)
visited_set.add(cur)
neighbours = self.graph[cur] # cur的临接点
for neighbour in neighbours:
if neighbour not in visited_set:
queue.append(neighbour)
visited_set.add(neighbour)
res.append(temp)
return res
if __name__ == '__main__':
search = Search(primalData(), 's')
res = search.BFS()
print(res)
# 输出展示:
[['s'], ['v', 'x'], ['u', 'w', 'y'], ['z']]
2. 其他图搜索资料
2.1 Dijkstra
适用范围:无负权重边
参考文章链接:有概念讲解
参考文章链接:有示例