图的广度优先遍历

来源:互联网 发布:中国实力知乎 编辑:程序博客网 时间:2024/04/29 20:34
#include<iostream>
using namespace std;
struct Map
{
int x;
int s;
};
int main()
{
Map map[10];
int book[10],e[10][10],n,m,a,b,cur,start,end,head,tail,flag=0;
cin>>n>>m;
for(int i=0;i<n;++i)//初始化图的邻接矩阵
{
for(int j=0;j<n;++j)
{
if(i==j)
e[i][j]=0;
else
e[i][j]=999;
}
}
for(int k=0;k<m;++k)//读入城市之间的航班
{
cin>>a>>b;
e[a][b]=1; //注意这里是无向图
e[b][a]=1;
}
head=tail=0; //队列初始化
map[tail].x=start;//从start城市出发
map[head].s=0;
tail++;
book[start]=1;
while(head<tail)//当队列不为空时循环
{
cur=map[head].x;//当前队列中首城市的编号
for(int h=0;h<n;++h)
{
if(e[cur][h]!=999&&book[h]==0)
{
map[tail].x=h;
book[h]=1;
tail++;
map[tail].s=map[head].s+1;//转机次数+1
}
if(map[tail].x==end)//如果到达目标城市,停止扩展
{
flag=1;
break;
}
}
if(flag==1)
break;
head++; //当一个节点扩展结束后,head++才能继续扩展
}
cout<<map[tail].s<<endl;
system("Pause");
return 0;
}
0 0
原创粉丝点击