Javatpoint Logo
Javatpoint Logo

Python Program to Detect a Cycle in a Directed Graph

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:

  • Topological sorting with cycle detection:

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:

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.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA