赞
踩
在图论中,环(英语:cycle)是一条只有第一个和最后一个顶点重复的非空路径。
在有向图中,一个结点经过两种路线到达另一个结点,未必形成环。
使用拓扑排序可以判断一个无向图中是否存在环,具体步骤如下:
使用拓扑排序判断无向图和有向图中是否存在环的区别在于:
使用 DFS 可以判断一个无向图和有向中是否存在环。深度优先遍历图,如果在遍历的过程中,发现某个结点有一条边指向已访问过的结点,并且这个已访问过的结点不是上一步访问的结点,则表示存在环。
我们不能仅仅使用一个 bool 数组来表示结点是否访问过。规定每个结点都拥有三种状态,白、灰、黑。开始时所有结点都是白色,当访问过某个结点后,该结点变为灰色,当该结点的所有邻接点都访问完,该节点变为黑色。
那么我们的算法可以表示为:如果在遍历的过程中,发现某个结点有一条边指向灰色节点,并且这个灰色结点不是上一步访问的结点,那么存在环。
#include #include #include using namespace std;vector<vector<int>> g;vector<int> color;int last;bool hasCycle;bool topo_sort() { int n = g.size(); vector<int> degree(n, 0); queue<int> q; for (int i = 0; i degree[i] = g[i].size(); if (degree[i] <= 1) { q.push(i); } } int cnt = 0; while (!q.empty()) { cnt++; int root = q.front(); q.pop(); for (auto child : g[root]) { degree[child]--; if (degree[child] == 1) { q.push(child); } } } return (cnt != n);}void dfs(int root) { color[root] = 1; for (auto child : g[root]) { if (color[child] == 1 && child != last) { hasCycle = true; break; } else if (color[child] == 0) { last = root; dfs(child); } } color[root] = 2;}int main() { int n = 4; g = vector<vector<int>>(n, vector<int>()); g[0].push_back(1); g[1].push_back(0); g[1].push_back(2); g[2].push_back(1); g[2].push_back(3); g[3].push_back(2); cout <endl; //0,无环 color = vector<int>(n, 0); last = -1; hasCycle = false; dfs(0); cout <endl; //0,无环 g[0].push_back(3); g[3].push_back(0); cout <endl; //1,有环 color = vector<int>(n, 0); last = -1; hasCycle = false; dfs(0); cout <endl; //1,有环 return 0;}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。