Dixtra algorithm (Dijkstra ' s algorithm)
Find the quickest path to use algorithm-the Dixtra algorithm (Dijkstra's algorithm).
Using the Dixtra algorithm step
(1) Find the cheapest node and get to the node within the shortest time.
(2) for the neighbor of the node, check if there is a shorter path to them, and if so, update its overhead.
(3) Repeat the process until each node in the diagram has done so.
(4) Calculate the final path.
Term weights (weight):
The Dixtra algorithm is used for graphs with numbers associated with each edge , which are called weights (weight).
Weighted Graph/non-weighted graph (weighted graph)
a graph with weights is called a weighted graph (weighted graph), and a graph without weights is called a non-weighted graph (unweighted graph).
To calculate the shortest path in a non-weighted graph, you can use breadth-first search. To calculate the shortest path in a weighted graph, you can use the Dixtra algorithm.
Ring
You can start from one node and go back to this node after a lap.
The non-directed graph means that two nodes point to each other, which is actually the ring!
The Dixtra algorithm is only applicable to a forward-free graph (directed Acyclicgraph,dag).
Negative right side
You cannot use the Dixtra algorithm with graphs that contain negative weights
The Dixtra algorithm assumes that, for a processed poster node, there is no shorter path to the node. This assumption is only true if there is no negative edge.
Realize
Example: Finding the shortest path from start to finish
#创建所有节点和路径的散列表graph ={' start ': {' A ': 6, ' B ': 2}, ' a ': {' fin ': 1}, ' B ': {' A ': 3, ' Fin ': 5}, ' Fin ': {}} #创建已知节点花销的散列表costs ={ ' A ': 6, ' B ': 2, ' fin ': float ("INF")} #float (' inf ') denotes positive infinity #储存父节点的散列表parents ={' a ': ' s Tart ', ' B ': ' Start ', ' Fin ': 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_c OST and node not in processed: #寻找花销最小, and no visited point lowest_cost = Cost Lowest_cost_node = node ret Urn Lowest_cost_nodenode = find_lowest_cost_node (costs) #找到花销最小的节点while node is not None: #这个w Hile loop after all nodes have been processed end cost = costs[node] Neighbors = Graph[node] for n in Neighbors.keys (): #遍历当前节点的所有 Neighbor new_cost = cosT + neighbors[n] #该节点到达该邻居的花销总和 if costs[n] > New_cost: #如果经当前节点前往该邻居更近 costs[n] = n Ew_cost #更新该邻居的花销 Parents[n] = node #同时将该邻居的父节点设置为当前节点 processed.append (node) #将当前节点标记为处理过 node = find_lowest_cost_node (costs) #找出接下来要处理的节点, and loop print (parents)
Summary
- Breadth-First search is used to find the shortest path in a non-weighted graph .
- The Dixtra algorithm is used to find the shortest path in a weighted graph .
- The Dixtra algorithm works only when the weights are positive.
- If the graph contains negative weights, use the Bellmannford algorithm
"Algorithm" Dixtra algorithm (Dijkstra ' s algorithm)