Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bellman-Ford :- Why are there N-1 iterations for calculating mindistance?

def calculateShortestPath(self,vertexList,edgeList,startVertex):
    startVertex.minDistance=0

    for i in range(0,len(vertexList)-1):#N-1 ITERATION
        for edge in edgeList:
            #RELAXATION PROCESS
            u=edge.startVertex
            v=edge.targetVertex
            newDistance=u.minDistance+edge.weight
            if newDistance<v.minDistance:
                v.minDistance=newDistance
                v.predecessor=u
    for edge in edgeList:# FINAL ITERATION TO DETECT NEGATIVE CYCLES
        if self.hasCycle(edge):
            print("NEGATIVE CYCLE DETECTED")
            self.HAS_CYCLE=True
            return

The above function is a part of the implementation of the Bellman-Ford Algorithm. My question is that how can one be sure that after N-1 iterations , the minimum distance has been calculated ? In case of Dijkstra it was understood that once the priority queue has gone empty all the shortest paths have been created but I can't understand the reasoning behind the N-1 over here.

N-Length of the Vertex List.
Vertex List-contains the different vertex.
EdgeList-List of the different Edges.

The implementation may be wrong since I read it from a tutorial video.Thanks For The Help


2 Answers

The outer loop executes N-1 times, because the shortest path can not contain more edges, otherwise the shortest path will contain a loop which can be avoided.

Minor: if you have N vertexes and N edges then at least 1 vertex is used twice, so such a path will contain a loop.

like image 189
yvs Avatar answered Dec 04 '25 23:12

yvs


The algorithm unlike Djkstra, is not greedy, but dynamic. In the first iteration of the loops it builds one possible path between two vertex and then at each iteration it improves the path by at least one edge. As the shortest path can use maximum n-1 edges, the iteration of the loop continues that much to find the shortest path.

For negative cycle, algorithm at nth iteration checks one more time to see if an edge exists to decrease the weight of the shortest path having n-1 edges. If yes, then that edge must be negative as the shortest path with all positive edges should be consisted of n-1 not n edges.

like image 21
shivangi gupta Avatar answered Dec 05 '25 00:12

shivangi gupta