输入样例:
6 8 2
1 2
2 3
3 4
4 5
5 6
6 4
3 6
1 5
输出样例:
2 3 1 6 4 5
思路:
又是一道很经典的模板题,只需要套BFS模板即可,唯一的考点就是表头插入法构造邻接表,可能在平时做题的时候都是用邻接矩阵,所以不太熟悉邻接表构图法。
参考《图和树的存储方式:邻接矩阵和邻接表》以了解邻接表和邻接矩阵,切莫搞混淆了。
我们使用二维数组来模拟邻接表,只不过第二维度用的是vector容器罢了,这样可以达到插入新的连接点的目的了。(如果用队列queue可能不方便迭代,vector更方便一些,看个人习惯,实现方法有千万种)
每次只需要索引到该点的vector容器,push_back进去即可。
有一个坑点(当然仅对于本实现方法来说),就是题目讲到是表头插入法,我们实现的是表尾插入法(push_back()),因此在所有数据输入完毕后,进行reverse操作即可。
BFS套模板,唯一不一样的就是此BFS时基于邻接表的基础之上的,不过万变不离其宗。
参考代码:
#include<bits/stdc++.h>
using namespace std;
int n, m, s;
const int MAXSIZE = 11;
vector<int> connect[MAXSIZE];
bool searched[MAXSIZE];
void bfs() {
queue<int> cur;
cur.push(s);
cout<<s<<" ";
int cnt = 1;
searched[s] = true;
while(cur.size()) {
queue<int> next;
while(cur.size()) {
int node = cur.front();
cur.pop();
// 遍历和该点相连接的点
for(auto nextNode:connect[node]) {
if(!searched[nextNode]) {
next.push(nextNode);
cout<<nextNode<<" ";
cnt++;
searched[nextNode] = true;
}
}
}
cur = next;
}
if(cnt != n) {
cout<<"\n0"<<endl;
}
}
int main() {
cin>>n>>m>>s;
while(m--) {
int from, to; cin>>from>>to;
connect[from].push_back(to);
connect[to].push_back(from);
}
for(int i=0;i<MAXSIZE;++i) {
reverse(connect[i].begin(), connect[i].end());
}
bfs();
return 0;
}