最短路径的一种算法
关键: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;
}
1326

被折叠的 条评论
为什么被折叠?



