题目描述
已知有向图G的顶点和边,输出图的宽度优先遍历结果(从1号结点开始)
输入
输入的第一行两个整数n,m。n表示节点个数,节点用1-n表示,m表示边的条数,第二行起的m行每行 有两个数s,t表示边的起点和终点。
(m<=10000,n,s,t<=100)
输出
图的宽度优先遍历结果(从1号结点开始),以空格隔开
样例
输入
8 9
1 2
1 3
1 4
2 5
3 5
4 5
5 6
6 4
7 8
输出
1 2 3 4 5 6 7 8
ACD代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> bfs(vector<vector<int>>& graph, vector<bool>& visited, int start) {
vector<int> result;
queue<int> q;
q.push(start); // 从start号结点开始遍历
visited[start] = true;
while (!q.empty()) {
int curr = q.front();
q.pop();
result.push_back(curr);
for (int neighbor : graph[curr]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
return result;
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> graph(n + 1);
vector<bool> visited(n + 1, false);
for (int i = 0; i < m; i++) {
int s, t;
cin >> s >> t;
graph[s].push_back(t);
}
vector<int> result;
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
vector<int> temp = bfs(graph, visited, i);
result.insert(result.end(), temp.begin(), temp.end());
}
}
for (int i : result) {
cout << i << " ";
}
cout << endl;
return 0;
}