图算法
图算法用于处理图结构数据。以下是常见的图算法及其 Python 实现:
1. Dijkstra 算法(最短路径)
Dijkstra 算法用于在带权图中找到从起点到所有其他节点的最短路径。它要求边的权重为非负数。
时间复杂度:
- 优先队列实现:O((V + E) log V),其中
V是节点数,E是边数。
Python 实现
import heapq
def dijkstra(graph, start):
distances = {
node: float('inf') for node in graph}
distances[start] = 0
priority_queue = [(0, start)]
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return distances
# 示例使用
graph = {
'A': {
'B': 1, 'C': 4},
'B': {
'A': 1, 'C': 2, 'D': 5},
'C': {
'A': 4, 'B': 2, 'D': 1},
'D': {
'B': 5, 'C': 1}
}
start_node = 'A'
distances = dijkstra(graph, start_node)
print(f"从节点 {
start_node} 出发的最短路径: {
distances}")
2. Floyd-Warshall 算法(所有节点对的最短路径)
Floyd-Warshall 算法用于计算图中所有节点对之间的最短路径。它支持负权边,但不能处理负权环。
时间复杂度:
- O(V³),其中
V是节点数。
Python 实现
def floyd_warshall(graph):
nodes = list(graph.keys())
n = len(nodes)
dist = [[float('inf')] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for u in graph:
for v in graph[u]:
dist[nodes.index(u)][nodes.index(v)] = graph[u][v]
for k in range(n):
for i in range(n):
for j in range(n):
dist[

最低0.47元/天 解锁文章
1172

被折叠的 条评论
为什么被折叠?



