dfs && bfs
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010, M = 100010;
struct Node
{
int id;
Node *next;
Node(int _id): id(_id), next(NULL){}
}*head[N]; //邻接表
bool st[N];
void add(int a, int b)
{
auto temp = new Node(b);
temp->next = head[a];
head[a] = temp;
}
void dfs(int i)
{
st[i] = true;
printf("%d ", i);
for(Node* p = head[i]; p; p = p->next)
{
int j = head[i]->id;
if(!st[j]) dfs(j);
}
}
void bfs(int i)
{
queue<int> q;
q.push(i);
st[i] = true;
while(!q.empty())
{
int j = q.front();
q.pop();
printf("%d ", j);
for(auto p = head[j]; p; p = p->next)
{
j = p->id;
if(!st[j])
{
st[j] = true;
q.push(j);
}
}
}
}
int main()
{
int n, m;
cin >> n >> m;
while (m -- )
{
int a,b;
cin >> a >> b;
add(a, b);
}
for (int i = 1; i <= n; i ++ )
{
if(!st[i])
{
bfs(i);
dfs(i);
}
}
return 0;
}