cmpe232_lecture_notes06
cmpe232_lecture_notes06
Lecture Notes
Özgür Özdemir
Istanbul Bilgi University
ozgur.ozdemir@bilgi.edu.tr
Week 06
Algorithm 1: Bellman-Ford Algorithm to find shortest paths from the given source vertex
Input: G : edge-weighted graph, s : source vertex, call : number of invoking the function
function BellmanFordSP(G, s):
dist ← initialize a vertices array and assign ∞ to each vertex
edges ← initialize an array of vertices
onQ ← initialize an array of vertices
queue ← initialize an empty regular queue
dist[s] ← 0
queue.enqueue(s)
onQ[s] ← true
while pq ̸= ∅ do
v ← queue.dequeue()
onQ[v] ← f alse
relax(G, v )
end function
function relax(G, v ):
foreach e ∈ G.Adj(v) do
n ← e.other(v)
if dist[n] > dist[v] + e.weight then
dist[n] ← dist[v] + e.weight
edges[n] ← e
if not onQ[n] then
queue.enqueue(n)
onQ[n] ← true
if call = G.V then ▷ to prevent never ending algorithm caused by negative cycles
detectNegativeCycle(G)
call++
end function
1
As given in Algorithm 1, the Bellman-Ford Algorithm may lead to an endless loop if the graph con-
tains negative cycles. The negative cycle refers to a cycle such that one turn causes a negative weight.
Since the distances decrease at each cycle turn, the updates will never be terminated. Therefore, a
control is required to prevent a never-ending algorithm.
2
B C
7 -5 5
5 A B
1 A F -8
2
8 C
D E
1
The shortest path obtained by the Bellman-Ford An example of a negative cycle having a path
Algorithm: A → C → F → E with the distance of A → B → C → A with the distance of -1.
10.