bool Shortest_Path_Faster_Algorithm(int source,int destination)//if by Adjacency Matrix is in O(N^3)
    {
        // Step 1: initialize graph
        AStack stk;
        LQueue<int> Q;
        int minDistanceMatrix[numVertex];
        int prevNode[numVertex];
        for (int i=0;i<numVertex;++i) prevNode[i]=UNDEFINED;
        for (int i=0;i<numVertex;++i) minDistanceMatrix[i]=INFINITY;
        minDistanceMatrix[source]=0;

        Q.enqueue(source);
        while (Q.length>0){
                int v=Q.dequeue();
                for (int w=first(v);w<numVertex;w=next(v,w)){
                    if (getWeight(v,w)+minDistanceMatrix[v]<minDistanceMatrix[w]){
                        minDistanceMatrix[w]=minDistanceMatrix[v]+getWeight(v,w);
                                            prevNode[w]=v;
                        Q.enqueue(w);
                    }
                }
        }
        cout<<minDistanceMatrix[destination]<<endl;
                cout<<source+1<<" ";
        while (prevNode[destination]!=UNDEFINED){
            stk.push(destination+1);
            destination=prevNode[destination];
        }
        while (stk.length()>0) cout<<stk.pop()<<" ";
        cout<<endl;
    }
Exemple #2
0
    void Dijkstra_Algorithm(int source,int destination)
    {
        AStack stk;
        int minDistanceMatrix[numVertex];
        int prevNode[numVertex];
        for (int i=0;i<numVertex;++i) minDistanceMatrix[i]=INFINITY;
        for (int i=0;i<numVertex;++i) prevNode[i]=UNDEFINED;
        minDistanceMatrix[source]=0;

        for (int i=0;i<numVertex;++i) mark[i]=UNVISTED;
        for (int i=0;i<numVertex;++i){
            int v=findMin(minDistanceMatrix);
            mark[v]=VISTED;
            for (int w=first(v);w<numVertex;w=next(v,w)){
                if (minDistanceMatrix[v]+getWeight(v,w)<minDistanceMatrix[w]) {
                    minDistanceMatrix[w]=minDistanceMatrix[v]+getWeight(v,w);
                    prevNode[w]=v;
                }
            }
        }
        cout<<minDistanceMatrix[destination]<<endl;
        cout<<source+1<<" ";
        while (prevNode[destination]!=UNDEFINED){
            stk.push(destination+1);
            destination=prevNode[destination];
        }
        while (stk.length()>0) cout<<stk.pop()<<" ";
        cout<<endl;
    }