Dijstra算法及数据读法

来源:互联网 发布:成都少儿编程培训机构 编辑:程序博客网 时间:2024/04/30 07:28

#include<iostream>
#include<iomanip>//输出格式头文件
#include<fstream>

#define N 5
#define MAXNUM 32767
using namespace std;
int Edge[N][N];
int s[N];
int path[N];
int dist[N];

void shortestPath(int V)
{
    int v=V;

    for(int i=0;i<N;i++)
    {
        dist[i]=Edge[v][i];
        s[i]=0;
        if(i!=v&&dist[i]<MAXNUM)
            path[i]=v;
        else
            path[i]=-1;
    }

    s[v]=1;dist[v]=0;
    for(i=0;i<N-1;i++)
    {
        int min=MAXNUM;int u=v;
        for(int j=0;j<N;j++)
            if(!s[j]&&dist[j]<min){u=j;min=dist[j];}
        s[u]=1;
        for(int w=0;w<N;w++)
            if(!s[w] && Edge[u][w]<MAXNUM && dist[u]+Edge[u][w]<dist[w])
            { dist[w]=dist[u]+Edge[u][w];
              path[w]=u;
            }
    /*  for(int k=0;k<N;k++)
              cout<<setw(10)<<setfill(' ')<<dist[k]<<setw(10)<<setfill(' ')<<s[k]<<setw(10)<<setfill(' ')<<path[k]<<endl;
         cout<<endl; */
    }
}


int main()
{
   for(int i=0; i<N; i++)
       for(int j=0;j<N;j++)
       {
           Edge[i][j]=0;
       }

   //从txt文件中读取数据到数组
   ifstream infile("D://VCSun//ShortestPath//array.txt",ios::in);
   for(i=0;i<N; i++)
   {
       for(int j=0;j<N;j++)
       {
           if(!infile.eof())
           infile>>Edge[i][j];
       }
   }

   //******************输出数组********************
   /*
   for(i=0; i<N; i++)
   {
       for(int j=0;j<N;j++)
       {
           cout<<setw(8)<<Edge[i][j];
       }
       cout<<endl;
   }
   */
   /*
       int U[N][N]={0,10,32767,30,100,
        32767,0,50,32767,32767,
        32767,32767,0,32767,10,
        32767,32767,20,0,60,
        32767,32767,32767,32767,0};
    */
   //**********************************************


    shortestPath(0);//顶点0到其它点的最短距离
    for(i=0;i<N;i++)
        cout<<dist[i]<<" "<<path[i]<<" "<<s[i]<<endl;
    return 0;
}