图的DFS和BFS遍历算法、图最短路径python

图的DFS和BFS遍历算法、图最短路径python_第1张图片
参考视频:https://www.bilibili.com/video/BV1Ks411575U

python 列表 [] 可以用来表示队列和栈,先进先出 pop(0),每次弹出第一位就行就可以表示队列,后进先出pop(),每次弹出最后一位就可以表示栈

图创立:

图的DFS和BFS遍历算法、图最短路径python_第2张图片
用字典构建,每个节点key,value是对应key的临接点

1、BFS广度优先遍历

def BFS(graph, s):
	queue = []
	queue.append(s) # 向list添加元素,用append()
	seen = set() # 此处为set, python里set用的是hash table, 搜索时比数组要快。
	seen.add(s) # 向set添加函数,用add()
	while (len(queue) > 0):
		vertex = queue.pop(0)
		nodes = graph[vertex]
		for w in nodes:
			if w not in seen:
				queue.append(w)
				seen.add(w)
		print(vertex)

BFS(graph, 'E')

2、DFS深度优先遍历

def DFS(graph, s):
	stack = []
	stack.append(s) # 向list添加元素,用append()
	seen = set() # 此处为set, python里set用的是hash table, 搜索时比数组要快。
	seen.add(s) # 向set添加函数,用add()
	while (len(stack) > 0):
		vertex = stack.pop()
		nodes = graph[vertex]
		for w in nodes:
			if w not in seen:
				stack.append(w)
				seen.add(w)
		print(vertex)

DFS(graph, 'E')

3、图最短路径

可以直接用BFS进行简单改写,增加parent字典,保存每个节点的前一个结点

假如要看到达B节点的最短路径

def BFS(graph, s):
	queue = []
	queue.append(s) # 向list添加元素,用append()
	seen = set() # 此处为set, python里set用的是hash table, 搜索时比数组要快。
	seen.add(s) # 向set添加函数,用add()
	parent = {s: None}

	while (len(queue) > 0):
		vertex = queue.pop(0)
		nodes = graph[vertex]
		for w in nodes:
			if w not in seen:
				queue.append(w)
				seen.add(w)
				parent[w] = vertex
		print(vertex)

BFS(graph, 'E')
v = 'B'  # 假如要看到达B节点的最短路径
while 'B' is not None:
	length =  []
	length.append(v)
	v = parent[v]

print(len(length) - 1)

你可能感兴趣的:(知识点)