DFS
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#define N 100010
int n, m;
int h[N], cnt;
int stack[N], top;
bool inStack[N];
int count[N];
bool ring;
struct edge{
int to;
int next;
}E[N];
void add(int v, int w){
E[++cnt].next = h[v];
E[cnt].to = w;
h[v] = cnt;
}
void topo_dfs(int x){
for(int i = h[x]; i != -1; i = E[i].next){
int j = E[i].to;
if(inStack[j]) continue;
count[j] = count[x] + 1;
if(count[j] >= n){
ring = true;
return;
}
topo_dfs(j);
}
stack[++top] = x;
inStack[x] = true;
}
int main(){
scanf("%d %d", &n, &m);
memset(h, -1, sizeof h);
for(int i = 1; i <= m; i++){
int x, y;
scanf("%d %d", &x, &y);
add(x, y);
}
if(ring) printf("-1");
else {
for (int x = 1; x <= n; x++)
if (!inStack[x]) topo_dfs(x);
if(top == n) for(int i = top; i >= 1; i--) printf("%d ", stack[i]);
else printf("-1");
}
return 0;
}
BFS
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#define N 100010
int n, m;
int h[N], cnt;
int d[N];
int que[N], head, tail;
struct edge{
int to;
int next;
}E[N];
void add(int v, int w){
E[++cnt].next = h[v];
E[cnt].to = w;
h[v] = cnt;
}
bool topological(){
for(int i = 1; i <= n; i++)
if(d[i] == 0)
que[++tail] = i;
while(head != tail){
int t = que[++head];
for(int i = h[t]; i != -1; i = E[i].next){
int j = E[i].to;
if(--d[j] == 0)
que[++tail] = j;
}
}
return tail == n;
}
int main(){
scanf("%d %d", &n, &m);
memset(h, -1, sizeof h);
for(int i = 1; i <= m; i++){
int x, y;
scanf("%d %d", &x, &y);
add(x, y);
d[y]++;
}
if(topological()){
for(int i = 1; i <= n; i++) printf("%d ", que[i]);
}
else printf("-1");
return 0;
}
还有个与BFS算法思想类似,维护一个栈的kahn算法