邻接表存储图的广度优先遍历
题目描述
试实现邻接表存储图的广度优先遍历。
输入
第一行分别为结点数n和边数m,第二行至第m+2行为边的信息,最后一行为遍历起始结点(无向图)
输出
见样例
输入样例:
7 9
0 2
0 3
0 4
1 3
1 5
2 3
2 5
4 5
5 6
2
输出样例:
BFS from 2: 2 0 3 5 4 1 6
参考代码:
#include <bits/stdc++.h>
using namespace std;
void BFS(int **p, int n, int start,vector<int> &path,bool *visited){
visited[start] = true;
vector<int> x;
for (int i = 0; i < n; i++) {
if (p[start][i] == 1 &&!visited[i]) {
visited[i] = true;
x.push_back(i);
path.push_back(i);
}
}
for (int i : x) {
BFS(p, n, i,path,visited);
}
}
int main() {
int n,m;
cin >> n >> m;
int **p = new int *[n];
for (int i = 0; i < n; i++) {
p[i] = new int[n];
memset(p[i], 0, sizeof(int)*n);
}
while (m--){
int x,y;
cin >> x >> y;
p[x][y] = 1;
p[y][x] = 1;
}
vector<int> path;
int start;
cin>>start;
bool *visited = new bool[n];
path.push_back(start);
memset(visited, false, sizeof(bool)*n);
BFS(p, n, start, path,visited);
cout<<"BFS from "<<start<<":";
while (path.size() < n){
start = find(visited, visited+n, false) - visited;
path.push_back(start);
BFS(p, n, start, path,visited);
}
for (int i : path) {
cout << ' ' << i;
}
return 0;
}