如果图形不包含任何循环,则它是一棵树。这是一个使用DFS检查有向图是否为树的C ++程序。
Begin function cyclicUtil() : a) Mark the current node as visited and part of recursion stack b)为与该顶点相邻的所有顶点递归。 c) Remove the vertex from recursion stack. function cyclic() : a) 将所有顶点标记为未访问且不属于递归堆栈 b) Call the CyclicUtill() function to detect cycle in different trees End
#include<iostream> #include <list> #include <limits.h> using namespace std; class G { int n; list<int> *adj; //contain adjacent list. bool CyclicUtil(int v, bool visited[], bool *rs); public: G(int V); // Constructor void addEd(int v, int w); bool cyclic(); }; G::G(int n) { this->n = n; adj = new list<int> [n]; } void G::addEd(int v, int u) //to add edges in the graph { adj[v].push_back(u); //add u to v’s list } bool G::CyclicUtil(int v, bool visited[], bool *recurS) { if (visited[v] == false) { visited[v] = true; //Mark the current node as visited and part of recursion stack recurS[v] = true; //为与该顶点相邻的所有顶点递归。 list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { if (!visited[*i] && CyclicUtil(*i, visited, recurS)) return true; else if (recurS[*i]) return true; } } recurS[v] = false; //Remove the vertex from recursion stack. return false; } //检查图是否为树 bool G::cyclic() { //将所有顶点标记为未访问且不属于递归堆栈 bool *visited = new bool[n]; bool *recurS = new bool[n]; for (int i = 0; i < n; i++) { visited[i] = false; recurS[i] = false; } // Call the CyclicUtill() function to detect cycle in different trees for (int i = 0; i < n; i++) if (CyclicUtil(i, visited, recurS)) return true; return false; } int main() { G g(4); g.addEd(0, 2); g.addEd(1, 2); g.addEd(2, 0); g.addEd(3, 2); if (g.cyclic()) cout << "Directed Graph isn't a tree"; else cout << "Directed Graph is a tree"; return 0; }
输出结果
Directed Graph isn't a tree