Bellman-Ford Algorithm
Dijkstra algorithm cannot judge the shortest path of a graph with negative weight edges.
If there is a negative weight, even if there is no negative weight loop, you can use the Bellman-Ford algorithm to find the shortest path.
PS: The negative weight loop indicates that the weight of the loop is negative.
Algorithm Description
1. Initialization: estimate the shortest distance of all vertices except the Source Vertex d [v] Starting + ∞, d [s] Starting 0;
2. iterative Solution: multiple relaxation operations are performed on each edge in edge set E to gradually approach the shortest distance of each vertex v in vertex set v; (run | v |-1 time)
3. Check the negative weight loop: Determine whether the two endpoints of each edge in edge set E converge. If unconverged vertices exist, the algorithm returns false, indicating no solution to the problem. Otherwise, the algorithm returns true, and the shortest distance of vertex v reachable from the source is saved in D [v.
Pseudocode:
1 for I = 1 to | g.v |-12 for each edge (u, v) belongs to G. e3 relax (U, V, W) 4 for each edge (u, v) belongs to G. e5 if (v. d> U. d + W (u, v) 6 RETURN false; 7 return true;
Time Complexity: O (VE) is the number of vertices * Number of Edges