<base href="http://10.1.5.253/acmhome/judge/problemdetail.jsp">
数据结构:图2(BFS遍历)
时间限制(普通/Java):1000MS/3000MS 运行内存限制:65536KByte
总提交:36 测试通过:22
总提交:36 测试通过:22
描述
从已给的连通图中某一顶点出发,沿着一些边访遍图中所有的顶点,且使每个顶点仅被访问一次,就叫做图的遍历。图的遍历的遍历有DFS和BFS两种。
上面的图,从顶点0出发,按照顶点序号从小到大的顺序BFS,得到遍历顺序为0 148 253 6 7。
输入
输入图的顶点个数与边数,以及每条边的两个顶点。
输出
BFS遍历顺序。
样例输入
910
01
12
23
14
04
08
85
54
56
67
样例输出
014825367
题目来源
hnldyhy
#include <iostream>
#include <queue>
using namespace std;
queue <int> my;
int m,n,map[100][100],bz[100],g=0;
void BFS(int k)
{ int t,i;
my.push(k);
bz[k]=1;
while(!my.empty())
{
t=my.front();g++;
my.pop();
if(g!=m)cout<<t<<" "; else cout<<t<<endl;
for(i=0;i<m;i++)
if(map[t][i]==1&&bz[i]==0)
{
bz[i]=1;
my.push(i);
}
}
}
int main()
{
int i=0,n,x,y,ans;
cin>>m>>n;
while (i<n)
{
cin>>x>>y;
map[x][y]=map[y][x]=1;
i++;
}
BFS(0);
return 0;
}