图论专题小结:拓扑排序

来源:互联网 发布:歌曲升降调软件 编辑:程序博客网 时间:2024/06/06 04:43

拓扑排序

拓扑排序是针对有向图进行的,拓扑排序有两个作用:(1)针对某种定义好的“小于”关系为结点排序;(2)判断一个有向图中是否存在有向环。我们可以利用DFS来完成拓扑排序。

下面是判断一个有向图g中是否含有有向环的代码:

#define N 100+10int c[N], g[N][N];//利用二维数组g保存有向图int n;//结点数,下标从0开始bool toposort(int u){c[u] = -1;//正在访问for (int v = 0; v < n; v++)if (g[u][v]){if (c[v] < 0)return true;//存在有向环,返回trueelse if (!c[v] && toposort(v))return true;}c[u] = 1;//访问结束return false;//不存在有向环}bool have_circle(){memset(c, 0, sizeof(c));for (int i = 0; i < n;i++)if (!c[i])if (toposort(i))return true;//存在有向环,返回truereturn false;//不存在有向环,返回false}


紫书上的代码

#define N 110int g[N][N];int c[N], topo[N], t;int n;//结点总数bool dfs(int u){c[u] = -1;for (int v = 0; v < 26;v++)if (g[u][v]){if (c[v] < 0)return false;if (!c[v] && !dfs(v))return false;}c[u] = 1;topo[--t] = u;return true;}bool toposort(){t = n;memset(c, 0, sizeof(c));memset(topo, 0, sizeof(topo)); for (int u = 0; u < n;u++)if (!c[u])if (!dfs(u))return false;return true;}


0 0