一个求最短路径的算法

最短路径的一种算法

关键:1,想到一个对称矩阵,数字表示距离 2假设从某点开走(如0,0点),将经过的路径值置为0   ,避免重复 3.当走完所有点时完成#include<iostream.h>
#include<stdlib.h>
#include<time.h>

const int N=8;
void display(int Array[][N],int row,int column)
{
   for(int j=0;j<column;j++)
   {
      cout<<" /tcode"<<j;
   }
   cout<<endl;
   for(int i=0;i<row;i++)
   {
    cout<<"code "<<i<<":/t";
    for(int j=0;j<column;j++)
     cout<<Array[i][j]<<"/t";    
   cout<<endl;
   cout<<endl;
   }
}
 
void displayResult(int tempPath[],int totalValue)
{
 cout<<"/nthe result is :"<<endl;
 cout<<"shortest path problem ,total value="<<totalValue<<endl;
 for(int i=0;i<N;i++)
  //cout<<tempPath[i]<<"/t";
 {
 
  cout<<"code "<<tempPath[i];
  if (i!=N-1)
  cout<<" —>";
 }
 cout<<endl;
 cout<<endl;
}
void calculate(int Array[][N],int row,int column)
{
 cout<<"calculate function"<<endl;
  int smallest=0,i=0,j=0,count=0,w=0;
  int tempPath[N]={-1},temp=0;
  int totalValue=0;
  for(i=0,count=0;count<column;count++)
  {
       i=temp;
    Array[i][0]=0;  
   
          j=0;//initial ,calculate from column zero
  
    while(j<column)//find the first number which is not zero (not compared)
    {
         if (Array[i][j]!=0)
   {
        smallest=Array[i][j];
     temp=j; //temp is recorded the column of the smallest,temporary smallest
        break;
   }
         else
           j++;
   //Array[i][0]=0;//add
    }
          while(j<column)
    {
     if(Array[i][j]<smallest&&Array[i][j]!=0)
     {
    temp=j;//temp  recorded the column of the smallest,the really smallest
                smallest=Array[i][j];
     }
     else
              {
      j++;
     }
    }
     
   Array[i][temp]=0;//this path has been passed
   Array[temp][i]=0;//this path has been passed
  
   for(int k=0;k<N;k++)
   {
    Array[k][temp]=0;
   }
 
   cout<<" [row "<<i<<" column "<<temp<<"]/tsmallest value="<<smallest<<"/tcode"<<i<<"-->code"<<temp<<endl;
   tempPath[w]=i;
   w++;
   totalValue+=smallest;
  }
  totalValue-=smallest;
 displayResult(tempPath,totalValue);  
}

int  main()
{
 cout<<"________the shortest path problem________"<<endl;
 int Array[N][N]={0};
 int i=0,j=0;
    time_t t;
    srand((unsigned) time(&t));
 for(i=0;i<N;i++)
  for(j=0;j<N;j++)
  {
   Array[i][j]=rand()%30;
   Array[j][i]=Array[i][j];
   if (i==j)
      Array[i][j]=0;
  }
   
    display(Array,N,N);
    calculate(Array,N,N);
 //display(Array,N,N);//for test ,to watch the result  array
cin.get();   
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值