#include <iostream> #include <queue> using namespace std; const int N=20; int g[N][N],bz[N]={0},n,flag=0; void bfs(int x) { int t,i; queue <int> q; q.push(x); bz[x]=1; while (!q.empty()) { t=q.front(); q.pop(); if (flag==0) { cout<<t; flag=1;} else cout<<" "<<t; for (i=0; i<n; i++) if (g[i][t]==1 && bz[i]==0) { q.push(i); bz[i]=1;} } } int main(int argc, char *argv[]) { int i,t,x,y; cin>>n>>t; for (i=1; i<=t; i++) { cin>>x>>y; g[x][y]=g[y][x]=1; } bfs(0); cout<<endl; return 0; }
#include <iostream>
#include <queue>
using namespace std;
const int N=20;
int g[N][N],bz[N]={0},n,flag=0;
void bfs(int x)
{
int t,i;
queue <int> q;
q.push(x); bz[x]=1;
while (!q.empty())
{
t=q.front(); q.pop();
if (flag==0)
{ cout<<t; flag=1;}
else cout<<" "<<t;
for (i=0; i<n; i++)
if (g[i][t]==1 && bz[i]==0)
{ q.push(i); bz[i]=1;}
}
}
int main(int argc, char *argv[])
{
int i,t,x,y;
cin>>n>>t;
for (i=1; i<=t; i++)
{ cin>>x>>y; g[x][y]=g[y][x]=1; }
bfs(0);
cout<<endl;
return 0;
}
#include <iostream> #include<queue> using namespace std; const int N=20; int g[N][N],bz[N]={0}; int n; void bfs(int x) { int t,i; int c=0; queue<int>q; q.push(x); bz[x]=1; while(!q.empty()) { t=q.front(); q.pop();c++; if(c==1)cout<<t; else cout<<" "<<t; for(i=0;i<n;i++) if(g[i][t]==1 && bz[i]==0){ q.push(i); bz[i]=1;} } } int main(int argc, char *argv[]) { int i,t,x,y; cin>>n>>t; for(i=1;i<=t;i++) { cin>>x>>y; g[x][y]=g[y][x]=1; } bfs(0); cout<<endl; return 0; }
#include <iostream>
#include<queue>
using namespace std;
const int N=20;
int g[N][N],bz[N]={0};
int n;
void bfs(int x)
{
int t,i;
int c=0;
queue<int>q;
q.push(x); bz[x]=1;
while(!q.empty())
{ t=q.front(); q.pop();c++;
if(c==1)cout<<t;
else cout<<" "<<t;
for(i=0;i<n;i++)
if(g[i][t]==1 && bz[i]==0){ q.push(i); bz[i]=1;}
}
}
int main(int argc, char *argv[])
{
int i,t,x,y;
cin>>n>>t;
for(i=1;i<=t;i++)
{
cin>>x>>y;
g[x][y]=g[y][x]=1;
}
bfs(0);
cout<<endl;
return 0;
}
原文:http://www.cnblogs.com/2014acm/p/3898686.html