File size: 2,418 Bytes
8a2dcce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | TOPIC: Bellman-Ford Algorithm
DEFINITION: The Bellman-Ford algorithm is a graph search algorithm that finds the shortest path from a source vertex to all other vertices in a weighted graph. It can handle negative weight edges and can detect negative weight cycles, making it a versatile tool for solving various graph-related problems. This algorithm is particularly useful for finding the shortest path in graphs where the edge weights can be negative.
TIME_COMPLEXITY: The time complexity of the Bellman-Ford algorithm is O(VE), where V is the number of vertices and E is the number of edges, because it relaxes all edges V-1 times.
SPACE_COMPLEXITY: The space complexity is O(V), as the algorithm needs to store the distance to each vertex from the source vertex.
USE_WHEN: The Bellman-Ford algorithm is the right tool when you need to find the shortest path in a graph with negative weight edges, or when you need to detect negative weight cycles. It's particularly useful in scenarios where other algorithms like Dijkstra's may fail due to negative weights.
AVOID_WHEN: You should avoid using the Bellman-Ford algorithm when the graph is very large and dense, as its O(VE) time complexity can be slow, and in such cases, more efficient algorithms like Dijkstra's or A* may be more suitable for graphs with non-negative weights.
EXAMPLE:
Let's consider a graph with 4 vertices (A, B, C, D) and 5 edges:
A -> B (weight: -1)
A -> C (weight: 4)
B -> C (weight: 3)
B -> D (weight: 2)
C -> D (weight: 2)
Initially, the distance to all vertices is infinity, except for A which is 0.
A: 0
B: inf
C: inf
D: inf
After the first iteration:
A: 0
B: -1
C: inf
D: inf
After the second iteration:
A: 0
B: -1
C: 2
D: inf
After the third iteration:
A: 0
B: -1
C: 2
D: 1
After the fourth iteration, no changes occur, so we stop.
The shortest distances are:
A to B: -1
A to C: 2
A to D: 1
Checkmark: The shortest path from A to D is A -> B -> D with a total weight of 1.
REAL_WORLD_ANALOGY: The Bellman-Ford algorithm can be thought of as finding the cheapest route to travel between cities, where the cost of traveling between cities can sometimes be negative, such as getting a refund for a part of the journey.
SOURCE_NOTE: Concepts referenced from general knowledge of graph algorithms and data structures. |