DFS输出遍历顺序(邻接链表)
#include<bits/stdc++.h>
using namespace std;
const int N = 1000;
int path[N], h[N], e[N], ne[N], n, m;
int idx = 1;
bool st[N];
int cnt;
void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++ ;
}
void dfs(int u, int step){
st[u] = 1;
path[cnt++] = u;
for(int i = h[u]; i != -1; i = ne[i]){
int j = e[i];
if(!st[j]){
dfs(j, step + 1);
}
}
}
int main(){
memset(h, -1, sizeof h);
cin >> n >> m;
while(m -- ){
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
}
dfs(1, 1);
for(int i = 0; i < cnt; i ++ ) printf("%d ", path[i]);
return 0;
}