Python Program to Detect a Cycle in a Directed Graph29 Aug 2024 | 4 min read Detecting cycles in a directed graph is a classic problem in computer science. There are several algorithms to solve this problem, but one of the most common is the depth-first search (DFS) algorithm. The basic idea of the DFS algorithm is to start at a vertex and explore as far as possible along each branch before backtracking. During this process, the algorithm marks each visited vertex as "discovered" and keeps track of the vertices on the current path in a stack. If it encounters a vertex that is already discovered and, on the stack, then a cycle exists in the graph. Python program for detecting cycles using DFS: Output: True False Explanation: The first graph has a cycle (A->C->A), while the second graph does not. The has_cycle function takes a dictionary representing the graph, where each key is a node and the corresponding value is a list of its neighbors. For example, the graph {'A': ['B', 'C'], 'B': ['C'], 'C': ['A']} represents a directed graph with edges A->B, A->C, and C->A. The function initializes two sets: visited to keep track of the visited vertices, and stack to keep track of the vertices on the current path. After that, it defines a nested DFS function that takes a node and returns "True" if a cycle is detected, and False otherwise. The DFS function first marks the node as visited and adds it to the stack. After that, it recursively calls itself on each neighbor of the node that has not been visited yet. A cycle exists if a neighbor is already visited and on the stack, and the function returns the "True" value. If no cycle is detected for the current node, it removes it from the stack and returns False. The outer loop in the has_cycle function simply iterates over all nodes in the graph and calls the DFS function on any unvisited node. If a cycle is detected, the function returns True; otherwise, it returns False. Time Complexity: The DFS algorithm visits every vertex and every edge exactly once, so its time complexity is O(V + E), where V is the number of vertices and E is the number of edges in the graph. In the worst case, the algorithm may visit all edges in the graph, which gives O(V^2) time complexity for a fully connected graph. Space Complexity: The space complexity of the DFS algorithm depends on the size of the graph and the maximum depth of the recursion stack. In the worst case, where the graph is a straight line, the stack may contain all vertices, giving a space complexity of O(V). However, the maximum depth of the stack is usually much less than V, so the space complexity is often much lower. In the implementation provided, we are using two sets: visited and stack, both of which can store at most V elements. Additionally, we have a recursive call stack that can have a maximum depth of V. Therefore, the space complexity of the algorithm is O(V). In summary, the DFS algorithm is a very efficient algorithm for detecting cycles in a directed graph. Its time complexity is O(V + E), and its space complexity is O(V). There are different approaches for detecting cycles in a directed graph. Here are two more approaches:
In a directed acyclic graph (DAG), we can perform a topological sort of the nodes, which orders the nodes so that all edges point from earlier to later nodes. If the graph has a cycle, then it cannot be topologically sorted. Therefore, we can modify the topological sort algorithm to detect cycles while building the sort order. This approach has a time complexity of O(V + E), where V is the number of vertices and E is the number of edges in the graph.
Tarjan's algorithm is another popular algorithm for detecting cycles in a directed graph. It is based on the concept of strongly connected components (SCCs) of the graph. An SCC is a subset of nodes in the graph where every node is reachable from every other node in the subset. Tarjan's algorithm performs a modified DFS on the graph and identifies the SCCs. If any SCC contains more than one node, the graph has a cycle. This approach has a time complexity of O(V + E), where V is the number of vertices and E is the number of edges in the graph. |
Automating repetitive jobs is a great idea. Developers and system administrators frequently use shell scripts to automate recurring processes like health checks and file backups. However, shell scripts could become more difficult to maintain as those activities get more complicated. Thankfully, Python can be used for...
22 min read
Finding Greater Element in Python In this problem, we will be given an array of integers, and we have to find the Greater Element for every element of each element of the array. The Greater Element is the first element on the right-hand side of...
10 min read
The Python interpreter is commercially used throughout many industries for source coding, computer programming, and code testing. It takes the commands from the user and executes them after interpreting them. Hence, it becomes very important to know about the version of Python interpreter that we are...
4 min read
In this tutorial, we will write the Python code to flattening the given linked list. A given linked list which consists of every node represents a linked list and contains two pointers of its type. The first pointer represents the pointer to the node and...
6 min read
Python is one of the most trending programming languages right now. Learning Python is not as hard as learning any other procedural language, given its simplified syntaxes, dynamic typing, and oops nature. There are a lot of sources on the web providing beginners a get start...
3 min read
The OrderedDict is the subclass of the dict object in Python. The difference between dict and OrderedDict is that the OrderedDict itself maintains the orders of the keys as inserted, whereas in the dict, the order of the keys is not an important part. The OrderedDict...
4 min read
In this tutorial, we will explain how to import datasets with Sklearn within PyBrain. A Dataset can be described as the collection of data that could be used to test, validate as well as train networks. When compared with arrays that are considered to be more flexible,...
2 min read
Context managers are an important tool in Python for managing resources and ensuring proper cleanup after the resources have been used. The statement in Python provides a convenient syntax for using context managers. However, sometimes we need to use context managers with additional arguments; for this,...
9 min read
Aho-Corasick is a kind of a dictionary-matching algorithm. This algorithm is used to search for words present in the keywords set. This algorithm is fast and efficient for finding words and their location. The Aho-Corasick algorithm builds an existing system and employs the TRIE notion. A tree...
7 min read
Introduction Urban planning and environmental tracking benefit greatly from using geospatial data, which is information about locations on the surface of the Earth. The Folium module is one of Python's greatest geographic data manipulation and visualization tools. A Python module called Folium makes it easier to make...
4 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India