输入:
连接点:
0 1
0 2
1 3
3 5
3 4
5 4
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
vector<vector<int> > g(N);
vector<int> res;
bool st[N]={false};
int main()
{
cout<<"请依次输入图的节点数、边数、遍历起点!"<<endl;
int n,m,v0;
cin>>n>>m>>v0;
cout<<"请连接节点!"<<endl;
while(m--)
{
int a,b;
cin>>a>>b;
g[a].push_back(b);
g[b].push_back(a);
}
queue<int>q;
q.push(v0);
st[v0]=true;
while(!q.empty())
{
int t=q.front();
res.push_back(t);
q.pop();
for(int i=0;i<g[t].size();i++)
if(!st[g[t][i]])
{
st[g[t][i]]=true;
q.push(g[t][i]);
}
}
if(res.size()<n) cout<<"该图不能遍历完!";
else
{
cout<<"图的广度优先遍历顺序是:";
for(int i=0;i<res.size();i++) cout<<res[i]<<" ";
}
return 0;
}