Geeks-detect cycle in a Directed Graph

Source: Internet
Author: User

Detect cycle in a Directed Graph

To determine whether a graph has a ring, see the following:


The only note here is that this is a directed graph, and the edges form a ring, which is not necessarily a ring, because the direction can be inconsistent.

Here we add an array to save the path information recstack [] that has already been asked by the queue.

The visited [] array is the information of vertices that have been asked by the observer. The functions of the two are different.

Knowing this knowledge point makes this question very easy.

Original article:

Http://www.geeksforgeeks.org/detect-cycle-in-a-graph/


# Include <stdio. h> # include <list> # include <limits. h ># include <iostream> using namespace STD; Class detectcycleinadirectedgraph {int size; List <int> * adj; bool iscycleutil (int v, bool visited [], bool * recstack) {If (! Visited [v]) {// clever question: Add recstack, because it is directed, if it is undirected, then we don't really need recstack. visited [v] = recstack [v] = true; List <int >:: iterator it = adj [v]. begin (); For (; it! = Adj [v]. End (); It ++) {If (! Visited [* It] & iscycleutil (* It, visited, recstack) return true; else if (recstack [* It]) return true ;} recstack [v] = false;} return false;} public: detectcycleinadirectedgraph (int v): size (v) {adj = new list <int> [size];} void addedge (int v, int W) {adj [v]. push_back (w);} bool iscyclic () {bool * visited = new bool [size]; bool * recstack = new bool [size]; fill (visited, visited + size, false); fill (recstack, recstack + size, false); For (INT I = 0; I <size; I ++) {If (iscycleutil (I, visited, recstack) return true;} return false;}; void detectcycleinadirectedgraph_run () {detectcycleinadirectedgraph g (4); G. addedge (0, 1); G. addedge (0, 2); G. addedge (1, 2); G. addedge (2, 0); G. addedge (2, 3); G. addedge (3, 3); If (G. iscyclic () cout <"graph contains cycle \ n"; elsecout <"graph doesn't contain cycle \ n ";}



Geeks-detect cycle in a Directed Graph

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.