📅  最后修改于: 2023-12-03 15:13:38.883000             🧑  作者: Mango
The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single source vertex to all of the other vertices in a weighted directed graph. It is slower than Dijkstra's algorithm for the same problem, but more versatile, as it is capable of handling graphs in which some of the edge weights are negative numbers.
The algorithm initializes the distance to the source vertex as 0 and all other distances as infinite. It then proceeds to relax all the edges in the graph in the order of increasing edge length. This process is repeated for V-1 times, where V is the number of vertices in the graph. The reason for this is that the longest possible path in a connected graph can have at most V-1 edges. After V-1 iterations, if there are still edges that can be relaxed, then the graph contains a negative-weight cycle.
function bellmanFord(G, s)
dist[s] <- 0
for i <- 1 to |V| - 1
for each edge (u, v, w) in E
if dist[u] + w < dist[v]
dist[v] <- dist[u] + w
for each edge (u, v, w) in E
if dist[u] + w < dist[v]
//negative weight cycle exists
The Bellman–Ford algorithm has a time complexity of O(V*E), where V is the number of vertices and E is the number of edges. This is because the algorithm has to relax all the edges V-1 times.
The Bellman–Ford algorithm can be used in various applications, such as:
The Bellman–Ford algorithm is a powerful algorithm for finding shortest paths in a graph, even when the graph has negative edge weights. While it is slower than Dijkstra's algorithm, it is more versatile and can be used in a variety of applications.