Welcome to this comprehensive guide on detecting cycles in a directed graph using Depth-First Search (DFS) and a stack! By the end of this lesson, you'll be able to navigate through a graph like a pro šÆ.
A directed graph is a collection of vertices (or nodes) and edges, where the edges have a direction from one vertex to another. In contrast to an undirected graph, the relationship between vertices in a directed graph is one-way.
Detecting cycles in a directed graph is essential in various real-world scenarios, such as checking the validity of a computer network, validating a program's flow, or finding the shortest path in a transportation network.
DFS is a popular algorithm for traversing graphs. We'll be using a stack to perform the traversal in this lesson. Let's dive in!
Initialize a stack and mark all vertices as unvisited. Set the current vertex as the first vertex to explore.
stack = []
visited = [False] * vertices_count
current_vertex = 0Push the current vertex onto the stack and mark it as visited.
stack.append(current_vertex)
visited[current_vertex] = TrueFor each adjacent vertex of the current vertex, recursively call the DFS function if it's not visited yet.
for adjacent in adjacency_list[current_vertex]:
if not visited[adjacent]:
dfs(adjacency_list, visited, stack, adjacent)If there are no more unvisited adjacent vertices for the current vertex, pop the vertex from the stack. This indicates that we have completed traversing the connected component of the graph containing the current vertex.
if len(stack) > 0:
current_vertex = stack.pop()
else:
returnIf the DFS process finds a cycle, the current vertex will be popped from the stack and pushed back again before the traversal is complete. This scenario indicates a cycle in the directed graph.
if current_vertex == stack[-1]:
print("Cycle found!")
returnLet's look at a practical example to solidify our understanding.
vertices_count = 6
adjacency_list = [
[],
[2, 3],
[0, 4],
[0, 5],
[1, 5],
[1]
]
def dfs(adjacency_list, visited, stack, current_vertex):
# Your DFS implementation goes here
...
dfs(adjacency_list, visited, stack, 0)In this example, the directed graph contains 6 vertices and edges between them. If you run the DFS algorithm on this graph, you'll find a cycle between vertices 0, 1, and 0 again.
Which of the following options correctly represents the purpose of detecting cycles in a directed graph?
By now, you should have a good understanding of how to detect cycles in a directed graph using DFS and a stack. Happy coding! š”šÆ