BFS和Dijkstra算法都是最短路径算法,在不同情况下它们的运行时间各有优劣。一般而言,BFS比Dijkstra算法运行时间更短,但是BFS不适合处理边权重不同的图。
下面是Python代码示例,比较了BFS和Dijkstra算法在不同情况下的运行时间:
import time
import heapq
from collections import deque
class Graph:
def __init__(self):
self.vertices = {}
def add_vertex(self, name, edges):
self.vertices[name] = edges
# BFS algorithm
def short_path_bfs(self, start, end):
visited = {start}
queue = deque([(start, 0)])
while queue:
vertex, distance = queue.popleft()
if vertex == end:
return distance
for neighbor in self.vertices[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, distance+1))
# Dijkstra's algorithm
def short_path_dijkstra(self, start, end):
heap = [(0, start)]
visited = set()
while heap:
(cost, vertex) = heapq.heappop(heap)
if vertex in visited:
continue
visited.add(vertex)
if vertex == end:
return cost
for (neighbor, c) in self.vertices[vertex].items():
if neighbor not in visited:
heapq.heappush(heap, (cost+c, neighbor))
# Testing BFS vs Dijkstra
g1 = Graph()
g1.add_vertex('A', {'B':1, 'C':4})
g1.add_vertex('B', {'A':1, 'C':2, 'D':5})
g1.add_vertex('C', {'A':4, 'B':2, 'D':1})
g1.add_vertex('D', {'B':5, 'C':1})
print("BFS running time:")
start_time = time.time()
print(g1.short_path_bfs('A', 'D'))
print("Elapsed time: %s seconds" % (time
下一篇:BFS回溯 - 孤立集群的情况