最短路徑python
在Python中,最短路徑問題可以使用多種算法來解決,其中一種常見的方法是使用Dijkstra算法。
下面是一個使用Dijkstra算法的示例代碼,它可以找到兩個節點之間的最短路徑:
import heapq
def dijkstra(graph, start, end):
# 初始化距離字典,將起點到所有節點的距離初始化為無窮大
distances = {node: float('infinity') for node in graph}
distances[start] = 0
# 初始化優先佇列,將起點加入佇列中
priority_queue = [(0, start)]
while priority_queue:
# 取出當前距離最小的節點
current_distance, current_node = heapq.heappop(priority_queue)
# 如果當前節點不是目標節點,則跳過
if current_node != end:
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
是一個字典,它的鍵是節點,值是一個字典,表示從起點到該節點的邊的權重。start
和end
是起點和終點節點的標識符。函式返回一個字典,其中包含從起點到所有其他節點的最短距離。
請注意,這個代碼示例僅適用於無向圖和加權邊的情況。如果您的圖是有向圖或無加權邊的情況,您需要使用不同的算法來解決最短路徑問題。