void Dijkstra()
{
int map[19][19]={0};
cout<<endl;
int path[19],dis[19],book[19];
map[1][3]=3;
map[2][3]=5;map[2][5]=6;
map[3][1]=3;map[3][2]=5;map[3][4]=2;map[3][6]=8;map[3][12]=10;
map[4][3]=2;map[4][7]=4;
map[5][2]=6;map[5][9]=4;map[5][6]=5;
map[6][3]=8;map[6][5]=5;map[6][10]=1;
map[7][4]=4;map[7][8]=2;
map[8][7]=2;map[8][12]=3;
map[9][5]=4;map[9][10]=6;map[9][18]=4;
map[10][6]=1;map[10][9]=6;map[10][11]=4;map[10][14]=4;
map[11][10]=4;map[11][12]=6;
map[12][8]=3;map[12][3]=10;map[12][16]=3;map[12][13]=5;
map[13][14]=2; map[13][12]=5;
map[14][10]=4; map[14][15]=2; map[14][13]=2;
map[15][14]=2; map[15][18]=1;
map[16][12]=3; map[16][17]=2;
map[17][16]=2; map[17][18]=3;
map[18][15]=1;map[18][9]=4; map[18][17]=3;
int s, e,k=0;
cout<<"请输入你需要查询的最短路径的起点和终点:"<<endl;
cin>>s>>e;
for(int i=1;i<=18;i++)
{
book[i]=0;
if(map[s][i]!=0)
dis[i]=map[s][i];//初始化path,dis和book
else dis[i]=inf;
if(dis[i]<inf)
path[i]=s;
else path[i]=-1;
}
book[s]=1;
path[s]=0;//初始化起点
dis[1]=0;
for(int i=1;i<=18;i++)
{
int min=inf;
for(int j=1;j<=18;j++)
{
if(book[j]==0&&dis[j]<min)
{
min=dis[j];
k=j;
}
}
book[k]=1;
for(int j=1;j<=18;j++)
{
if(map[k][j]!=0)
{
if(dis[j]>dis[k]+map[k][j])
{
dis[j]=dis[k]+map[k][j];
path[j]=k;
}
}
}
}
int l[20];
int t,i=1;
t=e;
cout<<"你所要的信息如下"<<endl;
l[i]=e;
while(path[t]!=0)
{
//cout<<i<<" "<<endl;
i++;
l[i]=path[t];
t=path[t];
}
cout<<"最短路径的距离是: "<<dis[e]<<endl;
cout<<"最短路径经过的景点个数有: "<<i<<"个"<<endl;
cout<<"从"<<s<<"到"<<e<<"的最短路径的路线是: ";
cout<<endl;
for(int j=i;j>=1;j--)
{
cout<<l[j];
if(j>1) cout<<"->";
}
}
int main()
{
Dijkstra();
system("pause");
}
最短路径Dijkstra
最新推荐文章于 2024-09-16 17:46:36 发布