用来进行确定前驱关系。
比如a < b , c < d, c < b 可以确定
a < c < b < d
或者
c < a < b < d
如果没有环的话一定可以存在一条这样的链,但是如果有环就不能进行拓扑排序。这个例子就是不能 a > b 且 b > a;
使用dfs 进行
伪代码
//判断是否有环(true 没有; false 有)
bool dfs(u) {
本趟节点标记;
for(遍历以u为入弧的定点){
if(是本趟节点)return false;
else if(如果没访问过) {
if(子节点有环)return false;
}
}
//表示这个节点的到底都没有环
倒着将沿途的节点加入拓扑队列 //因为这是递归的返回,就是到头回来的过程
return true;
}
bool topoSort(){
for(遍历节点){
if(没访问过){
if(有环) return false;
}
}
//所有节点都没环
return true;
}
两句if 可以合成为
if(没访问过 && 有环)return false;
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 100;
int c[maxn];
int topo[maxn], t, n;
int G[maxn][maxn];
bool dfs(int u)
{
c[u] = -1;
for(int v = 0; v < n; v++)
{
if(G[u][v])
{
if(c[v] < 0)
return false;
else if(!c[v] && !dfs(v))
return false;
}
}
c[u] = 1;
topo[--t] = u;
return true;
}
bool topoSort()
{
t = n;
memset(c,0,sizeof(c));
for(int u = 0; u < n; u++){
if(!c[u] && !dfs(u))
return false;
}
return true;
}
int main()
{
char ch[100] = {
'a', 'b', 'c', 'd'};
n = 4;
G[0][1] = 1;
//G[1][0] = 1;
G[2][1] = 1;
G[3][2] = 1;
if(!topoSort()){
printf("无法拓扑排序\n");
return 0;
}
for(int i = 0; i < 4; i++){
printf("%c ", ch[topo[i]]);
}
printf("\n");
}
这个代码最精彩的部分就是使用c[u] = -1判断本趟结果是否有环。
区别于经典的dfs标志数组用了两个值表示不同的意思。
c[u] = 0:表示每访问
c[u] = 1:表示上面为顶点的节点访问过
c[u] = -1 : 表示以本次dfs是否访问过