还有不要在dfs里传vector,肯定炸的TAT
供参考可交流
#define _CRT_SECURE_NO_WARNINGS 1
//#include <bits/stdc++.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#include <unordered_map>
#include <vector>
#include <math.h>
#include <list>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <unordered_set>
#include <string>
#include <algorithm>//sort
#include <stdlib.h>
#include <iomanip>
#include <cstring>//memset
#include <limits.h>
/*ios::sync_with_stdio(false);
cin.tie(0);*/
int barr[100005] = { 0 };
vector<int>alist[100005];
int n, m;
void dfs(int cur)
{
barr[cur] = 1;
cout << cur << " ";
sort(alist[cur].begin(), alist[cur].end());
for (int x : alist[cur])
{
if (barr[x] == 0)
{
dfs(x);
}
}
}
int main()
{
//ios::sync_with_stdio(false);
//cin.tie(0);
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y; cin >> x >> y;
alist[x].push_back(y);
}
dfs(1);
cout << endl;
//bfs
memset(barr, 0, sizeof barr);
queue<int>q;
q.push(1);
barr[1] = 1;
while (q.size())
{
cout << q.front() << " ";
for (int x : alist[q.front()])
{
if (barr[x] == 0)
{
barr[x] = 1;
q.push(x);
}
}
q.pop();
}
return 0;
}