ディジェストラ最短経路アルゴリズム厳蔚敏C++実現

2657 ワード

#include <iostream>
using namespace std;
const int MAX=20;
const int INF=9999;
typedef bool PathMatrix[MAX+1][MAX+1];
typedef int ShortPathTable[MAX+1];
typedef struct
{
    int vexnum,arcnum;
    char vexs[MAX+1];
    int arcs[MAX+1][MAX+1];
}MGraph;

void Create_MG(MGraph &G)
{
    int i,j,v1,v2,w;//v1,v2,w              
    cout<<"          :"<<endl;
    cin>>G.vexnum>>G.arcnum;
    for(i=0;i<G.vexnum;i++)
        for(j=0;j<G.vexnum;j++)
            G.arcs[i][j]=INF;
    for(i=0;i<G.vexnum;i++)
    {
        cout<<"    "<<i<<"   :"<<endl;
        cin>>G.vexs[i];
    }
    for(i=1;i<=G.arcnum;i++)
    {
        cout<<"    --  :          "<<endl;
        cout<<"  0 2 10"<<endl;
        cin>>v1>>v2>>w;
        G.arcs[v1][v2]=w;
    }
}
void ShortestPath_DIJ(MGraph &G,int v0,PathMatrix &P,ShortPathTable &D)
{
    //    v0          P,      D
    //  P     ,     ,         (P[W][v] True   v0 
    //w   v,D     ,   v0        ((D[v] == 10  
    // v0 v         10) final           
    //(  final]v] TRUE      v0 v     )

    bool final[MAX];
    int v,w,j;
    for( v=0;v<G.vexnum;v++)
    {
        final[v]=false;
        D[v]=G.arcs[v0][v];
        for(w=0;w<G.vexnum;w++)
        {
            P[v][w]=false;//    
        }
        if(D[v]<INF)
        {
            P[v][v0]=true;
            P[v][v]=true;
        }
    }
    D[v0]=0;
    final[v0]=true;//   ,V0  S 
    //     ,     n-1     S 
     for(v=1;v<G.vexnum;v++)
    {
        int min=INF;
        for(w=0;w<G.vexnum;w++)
        {
            if(!final[w] && D[w]<min)//w V-S ,  v0    
            {
                min=D[w];
                v=w;
            }
        }
        final[v]=true;
        for(w=0;w<G.vexnum;w++)//           
        {
            //  D[w] P[w]   w V-S 
            if(!final[w] && min+G.arcs[v0][w]<D[w])
            {
                D[w]=min+G.arcs[v0][w];
                for(j=0;j<G.vexnum;j++)
                    P[w][j]=P[v][j];
                P[w][w]=true;
            }
        }

    }
}
int main()
{
    MGraph G;
    Create_MG(G);
    PathMatrix P;
    ShortPathTable D;
    ShortestPath_DIJ(G,0,P,D);
    for(int i=0;i<G.vexnum;i++)
    {
        cout<<"V0 "<<i<<"      :"<<endl;
        for(int j=0;j<G.vexnum;j++)
        {
            cout<<P[i][j];
        }
        cout<<"     "<<D[i]<<endl;
    }

}