In comparison, the Bellman-Ford algorithm needs to perform relaxation operations on all edges every time. The time complexity is O (the number of vertices * the number of edges), and it can handle negative-weight edges. However, in our real life, when calculating the path, It rarely encounters negative weight edges, so when only positive weight edges are considered, a more optimized Dijkstra algorithm can be used.
Dijkstra algorithm sets up two sets, and set all vertices set to V, then:
S=All vertices with the shortest path and the lowest weight value have been determined with the starting point s.
W=V-S。
The algorithm moves the vertex u with the smallest weight value in W into S every time, and performs relaxation operations on all edges of u.
Look at the picture and talk:
initialization:
S=A0
W=B∞,C∞,D∞,E∞,F∞,G∞
1. It is necessary to perform relaxation operations on all edges of A, the result
S=A0
W=B6,C4,D∞,E∞,F∞,G∞
2. Take out the smallest vertex C in W and put it into S, and perform relaxation operations on all edges of C. The result
S=A0,C4
W=B6,D9,E∞,F11,G∞
3. Take out the smallest vertex B in W and put it into S, and perform relaxation operations on all edges of B. The result
S=A0,B6,C4
W=D9,E11,F11,G∞
4. Take out the smallest vertex D in W and put it into S, and perform relaxation operations on all edges of D. The result
S=A0,B6,C4,D9
W=E11,F10,G∞
5. Take the smallest vertex F in W into S, and perform relaxation operations on all edges of F, the result
S=A0,B6,C4,D9,F10
W=E11,G∞
6. Take the smallest vertex E in W and put it into S, and perform relaxation operations on all edges of E. The result
S=A0,B6,C4,D9,E11,F10
W=G∞
7. Take out the smallest vertex G in W and put it into S, and perform relaxation operations on all edges of G. The result
S=A0,B6,C4,D9,E11,F10,G∞
So far, we can get a shortest path tree:
A——B=6
A——C=4
A——C——D=9
A——B——E=11
A——C——D——F=10
A无法到达G
There are two places to optimize here:
1. Because the vertices with the smallest weight are to be taken out, W must be sorted every time, and the algorithm of traversing the array for comparison is used. It is better to use the priority queue (PriorityQueue), because the priority queue uses a heap structure, and the sorting time complexity is O (nlgn).
2. If we just want to calculate the shortest distance from the starting point to a certain point, then when traversing, check whether the smallest vertex taken out is the end point, if it is, just jump out of the loop.