迪克斯拉特算法:
1、找出代價最小的節點,即可在最短時間內到達的節點;
2、更新節點的鄰居的開銷;
3、重復這個過程,直到圖中的每個節點都這樣做了;
4、計算最終路徑。
'''
迪克斯特拉算法:
1、以字典的方式更新圖,包括權重
2、創建開銷字典,關鍵在於起點臨近的點開銷為實際數值,其他點為暫時未到達,開銷為無窮,隨后更新
3、創建父節點列表保存每個點的父節點,以便記錄走過的路徑
'''
from queue import LifoQueue
graph = {}
graph['start'] = {}
graph['start']['a'] = 6
graph['start']['b'] = 2
graph['a'] = {}
graph['a']['end'] = 4
graph['b'] = {}
graph['b']['a'] = 3
graph['b']['c'] = 2
graph['c'] = {}
graph['c']['end'] = 3
graph['end'] = {}
print(graph)
infinity = float('inf')
costs = {}
costs['a'] = 6
costs['b'] = 2
costs['c'] = infinity
costs['end'] = infinity
parents = {}
parents['a'] = 'start'
parents['b'] = 'start'
parents['c'] = 'b'
parents['end'] = None
processed = []
def find_lowest_cost_node(costs):
lowest_cost = float('inf')
lowest_cost_node = None
for node in costs:
cost = costs[node]
if (cost < lowest_cost and node not in processed):
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
node = find_lowest_cost_node(costs)
while(node is not None):
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys():
new_cost = cost + neighbors[n]
if costs[n] > new_cost:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = find_lowest_cost_node(costs)
#輸出最短路徑
p = 'end'
path = LifoQueue()
while(True):
path.put(p)
if(p == 'start'):
break
p = parents[p]
while not path.empty():
print(path.get())
