Search code examples
javaperformancedata-structuresshortest-pathbellman-ford

Bellman ford performance


   for(int k=1; k<=Vertices-1; k++){   
        /*Every sublist has found the shortest to its adjacent vertices
        thats why starting loop from k-1 then going into every edge of a vertex
        and updating the shortest distance from it to the other.
        */
        for(int i=k-1; i<Vertices; i++){
            // Visiting every Vertex(V) and checking distance of its edges to some other vertex Vo.
            for(int j=0; j<Edges[i].size(); j++){
                int v = Edges[i].get(j).src;
                int edge = Edges[i].get(j).dest;
                int weight = Edges[i].get(j).weight;
                // if exisiting distance is not infinity and from source to that vertex the weight is less then update it
                if (dist[v]!=Integer.MAX_VALUE && dist[v]+weight<dist[edge]){
                    dist[edge]=dist[v]+weight;
                    //updating parent of destination to source.
                    parent[edge] = v;
                }
            }
        }
    }

I have implemented bellman ford from list of (LinkedList) as the algorithm runs V-1(loop 1) times and going into every vertex(in Loop2) it checks all of it edges(in loop3) and update the distances of destinations.I'm confused here that the time complexity will still be O(VE) or changed,I have seen this work done in 2 loops thats why, and also will the shortest path be found for each vertex passing by or i have to start it from 0?


Solution

  • As far as you are checking all the edges for V time, the complexity is still O(VE). for further information read this.