BFS_最短路径

时间:2023-03-09 20:04:56
BFS_最短路径

已知若干个城市的地图,求从一个城市到另一个城市的路径,要求路径中经过的城市最少。

BFS_最短路径

#include<iostream>
#include<cstring>
using namespace std;
int ju[][]=
{{,,,,,,,,},
{,,,,,,,,},
{,,,,,,,,},
{,,,,,,,,},
{,,,,,,,,},
{,,,,,,,,},
{,,,,,,,,},
{,,,,,,,,},
{,,,,,,,,}};
int a[],b[],s[],head,tail;
void print(int d)
{
cout << char(a[d]+);
while(b[d]){
d=b[d];
cout << "--" << char(a[d]+);
}
cout << endl;
}
void bfs()
{
int i;
head=;tail=; //tail依次记录每个节点
a[]=;b[]=;s[]=; //a数组记录每个节点上城市,b数组记录上一个城市的节点,s记录走过的城市
do{
head++;
for(i=;i<=;i++){
if(ju[a[head]][i]== && s[i]==){
tail++;
a[tail]=i;
b[tail]=head;
s[i]=;
if(i==) {
print(tail);
return;
}
}
}
}while(head<tail);
}
int main()
{
memset(s,,sizeof(s));
bfs();
return ;
}