图的广度优先遍历
来源:互联网 发布:中国实力知乎 编辑:程序博客网 时间: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;
}
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
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的广度优先遍历
- 图的遍历-(深度优先&广度优先)
- 图的遍历:深度优先、广度优先
- 图的遍历-广度优先遍历
- 图的遍历- 广度优先遍历
- 图:图的遍历(深度优先遍历、广度优先遍历)
- PHP引用(&)使用详解
- PipedInputStream和PipedOutputStream管道流
- hdu 1018 log10()
- 基于json-lib.jar包 创建JSONObject的四个常用方法
- c++学习书籍指南
- 图的广度优先遍历
- [ 全家拍 ] 一本可与他人分享的日历相册
- 彻底解决Android 应用方法数不能超过65K的问题
- ubuntu12.04上live555+v4l2+ffmpeg+x264开发环境的搭建
- timus 2025. Line Fighting
- JFrame中的setDefaultCloseOperation
- 第1章 对象导论
- unity学习之数据库基础
- android工程的mk写法。