当前位置:   article > 正文

python最短路径算法及优化思路_python路径优化

python路径优化
  1. Dijkstra算法
  • 算法思路: 从起点出发,每次选择距离起点最近的未访问节点加入已访问集合,然后更新与其相邻的节点的距离
  • 优化思路: 堆优化, 预处理相邻节点, 双向Dijkstra
  • 代码示例:
  1. import heapq
  2. def dijkstra(graph, start):
  3. distances = {node: float('inf') for node in graph}
  4. distances[start] = 0
  5. heap = [(0, start)]
  6. while heap:
  7. (dist, current_node) = heapq.heappop(heap)
  8. if dist > distances[current_node]:
  9. continue
  10. for neighbor, weight in graph[current_node].items():
  11. distance = dist + weight
  12. if distance < distances[neighbor]:
  13. distances[neighbor] = distance
  14. heapq.heappush(heap, (distance, neighbor))
  15. return distances

  1. Bellman-Ford算法
  • 算法思路: 从源点出发,依次进行n-1轮更新,每次更新当前节点的所有邻居的距离
  • 优化思路: 提前退出, 差分约束系统求解
  • 代码示例:
  1. def bellman_ford(graph, start):
  2. distances = {node: float('inf') for node in graph}
  3. distances[start] = 0
  4. for _ in range(len(graph) - 1):
  5. for node in graph:
  6. for neighbor, weight in graph[node].items():
  7. if distances[node] + weight < distances[neighbor]:
  8. distances[neighbor] = distances[node] + weight
  9. return distances

  1. Floyd-Warshall算法
  • 算法思路: 以中间节点为枚举变量,更新任意两个节点之间的距离
  • 优化思路: 利用矩阵运算加速
  • 代码示例:
  1. def floyd_warshall(graph):
  2. distances = graph
  3. for k in graph:
  4. for i in graph:
  5. for j in graph:
  6. distances[i][j] = min(distances[i][j], distances[i][k] + distances[k][j])
  7. return distances

  1. A*算法
  • 算法思路: 综合考虑路径长度和启发函数值,每次选取最小值作为下一个搜索节点
  • 优化思路: 启发函数优化(如曼哈顿距离), 双向A*
  • 代码示例:
  1. import heapq
  2. from math import sqrt
  3. def euclidean_distance(a, b):
  4. return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
  5. def a_star(graph, start, end):
  6. open_set = set([start])
  7. closed_set = set()
  8. g = {node: float('inf') for node in graph}
  9. g[start] = 0
  10. parents = {node: None for node in graph}
  11. f = {node: euclidean_distance(graph[node], graph[end]) for node in graph}
  12. while open_set:
  13. current = min(open_set, key=lambda node: f[node])
  14. if current == end:
  15. path = []
  16. while current:
  17. path.append(current)
  18. current = parents[current]
  19. return list(reversed(path))
  20. open_set.remove(current)
  21. closed_set.add(current)
  22. for neighbor in graph[current]:
  23. if neighbor in closed_set:
  24. continue
  25. tentative_g_score = g[current] + euclidean_distance(graph[current], graph[neighbor])
  26. if neighbor not in open_set:
  27. open_set.add(neighbor)
  28. elif tentative_g_score >= g[neighbor]:
  29. continue
  30. parents[neighbor] = current
  31. g[neighbor] = tentative_g_score
  32. f[neighbor] = g[neighbor] + euclidean_distance(graph[neighbor], graph[end])
  33. return None

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/550185
推荐阅读
相关标签
  

闽ICP备14008679号