Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must return true.
Solution
Depth First Traversal can be used to detect cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is from a node to itself (selfloop) or one of its ancestor in the tree produced by DFS. In the following graph, there are 3 back edges, marked with cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph.
For a disconnected graph, we get the DFS forrest as output. To detect cycle, we can check for cycle in individual trees by checking back edges.
To detect a back edge, we can keep track of vertices currently in recursion stack of function for DFS traversal. If we reach a vertex that is already in the recursion stack, then there is a cycle in the tree. The edge that connects current vertex to the vertex in the recursion stack is back edge. We have used recStack[] array to keep track of vertices in the recursion stack.
class Graph { int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency lists bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic() public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isCyclic(); // returns true if there is a cycle in this graph }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } // This function is a variation of DFSUytil() in http://www.geeksforgeeks.org/archives/18212 bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack) { if(visited[v] == false) { // Mark the current node as visited and part of recursion stack visited[v] = true; recStack[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) ) return true; else if (recStack[*i]) return true; } } recStack[v] = false; // remove the vertex from recursion stack return false; } // Returns true if the graph contains a cycle, else false. // This function is a variation of DFS() in http://www.geeksforgeeks.org/archives/18212 bool Graph::isCyclic() { // Mark all the vertices as not visited and not part of recursion // stack bool *visited = new bool[V]; bool *recStack = new bool[V]; for(int i = 0; i < V; i++) { visited[i] = false; recStack[i] = false; } // Call the recursive helper function to detect cycle in different // DFS trees for(int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } int main() { // Create a graph given in the above diagram Graph 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"; else cout << "Graph doesn't contain cycle"; return 0; }
Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E).
Reference:
相关推荐
A cybersecurity knowledge graph can be paramount in aiding a security analyst to detect cyber threats because it stores a vast range of cyber threat information in the form of semantic triples which ...
detect-inapp, 在移动应用程序的应用程序信息中,检测浏览器或者 检测 InApp检测浏览器或者应用程序的应用程序信息 代码示例import InApp from 'detect-inapp';const inapp = new InApp(navigato
本文将深入探讨“VMP detect bug in hook(KM/UM)”这一主题,它涉及到如何在内核模式(KM)和用户模式(UM)下检测反反调试工具。 首先,让我们理解什么是钩子(Hook)。钩子是编程中的一个概念,允许我们监控和...
image acquisition device to detect motion in the live video. It uses the optical flow estimation technique to estimate the motion vectors in each frame of the live video sequence
CVPR2007_Learning_to_detect_a_salient_object论文源代码
培训_YOLOv5YOLOv9_to_detect_fire_in_a_video_yolov5-fire检测_Training_YOLOv5YOLOv9_to_detect_fire_in_a_video_yolov5-fire-detection
### 学习检测显著物体:图像显著性检测的深度解析 #### 摘要与背景 本文探讨了视觉注意力在图像处理中的应用,通过检测图像中的显著物体来模拟人类视觉系统对特定区域的关注机制。作者将显著物体检测视为一种图像...
检测一个图是否有环
THe FiberToolbox is a plugin for DREAM.3D that allows the user to extract ellipses from a 2D image. The plugin was primarily developed to extract fibers from a micrograph cross section of a Composite ...
a new automatic target detection (ATD) algorithm to detect targets such as military targets, vehicle detection, oil storeroom detection. This algorithm uses concentric circles to extract features of ...
`Mobile-Detect-in-php` 是一个用于检测客户端设备的库,它可以帮助开发者轻松识别用户是通过移动设备、平板电脑还是个人电脑访问网站。在这个项目中,我们将探讨如何使用这个库来实现设备检测,并了解其工作原理。 ...
《Detect It Easy(DiE):一款强大的打包识别工具》 在信息技术领域,软件安全是至关重要的一环。其中,对软件打包方式的识别是确保系统安全的重要步骤之一。"Detect It Easy(DiE)"就是这样一款专业且强大的工具,...
Mobile_Detect库的核心在于它能够检测多种设备特征,包括但不限于设备制造商(如Apple、Samsung)、操作系统(iOS、Android、Windows Phone)、设备类型(手机、平板、桌面电脑)以及浏览器类型。这些信息对于响应式...
Ping pong 协议中的一种更高效的窃听检测方法及其在量子秘密共享中的应用,高飞,郭奋卓,本文针对ping pong协议提出了一种更高效的窃听检测方法,它可以更全面的开发Bell态的作用,使得协议的安全性得到明显改善,...
《Detect It Easy 2.01:便捷的可执行文件分析工具》 在信息技术领域,安全分析和恶意软件检测是至关重要的环节。Detect It Easy(简称DIE)是一款专为IT专业人士设计的实用工具,其2.01版本进一步提升了在识别和...
$detect = new Mobile_Detect(); if ($detect->isMobile()) { // 加载移动设备的CSS和脚本 } elseif ($detect->isTablet()) { // 加载平板设备的CSS和脚本 } else { // 默认的桌面设备处理 } ``` Mobile-Detect...
include('sstn/mobile_device_detect.php'); mobile_device_detect(false,true,true,'m/index.php',false); 2、上传附件中的mobile_device_detect.php到sstn目录。没有就在根目录新建一个。 说明。代码中的"m...
《DetectitEasy:深入解析EXE程序检测工具》 在信息技术领域,理解并分析EXE(可执行)程序是至关重要的。DetectitEasy是一款专为此目的设计的强大工具,它能够帮助用户快速识别出EXE程序是由哪种编程语言和开发...
hand_inference_graph of using Neural Networks (SSD) on Tensorflow to do hand detect. https://github.com/molyswu/hand_detection
in this system for upper users: Summary Design Implemention Details GraphBuild N Degree Neighbours Visualization Custom attributes 要展示的属性标签客制化 Community Detection PageRank Second Degree ...