Performing DFS and BFS on a directed graph
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
To effectively navigate and analyze directed graphs, two foundational graph traversal algorithms are widely utilized: Depth-First Search (DFS) and Breadth-First Search (BFS). Understanding these algorithms' mechanisms, applications, and performance is essential for working with graph structures in various computational contexts.
Graph Representation
Before diving into DFS and BFS, it's essential to understand how a directed graph can be represented:
- Adjacency List: Typically used for sparse graphs, where an array or list is composed for each vertex, and each index contains a list of other vertices that are directly reachable.
- Adjacency Matrix: Suitable for dense graphs, this is a 2D array where rows represent source vertices, columns represent destination vertices, and cell values indicate the presence (often with weight) or absence (often zero) of an edge.
Depth-First Search (DFS)
Overview
Depth-First Search is an algorithm that traverses a graph in a depthward motion, exploring as far down through the vertices as possible before backtracking. It uses a stack data structure, either implicitly via recursion or explicitly.
Algorithm
- Start at a vertex.
- Explore an unvisited adjacent vertex, mark it as visited, and add it to the path.
- Recursively apply the above steps to each adjacent vertex.
- Backtrack when a vertex with no unvisited adjacent vertices is reached.
- Repeat until all vertices are visited.
Example
Consider the graph:
- Cycle Detection: Identify back edges that create cycles within the graph.
- Topological Sorting: Compute a linear ordering of vertices for DAGs (Directed Acyclic Graphs).
- Path Finding: Identify all possible paths between nodes.
- Shortest Path: Particularly useful in unweighted graphs for finding the shortest path.
- Level-Order Traversal: Like level-order traversal in trees.
- Connected Components: Discover all connected components in a non-connected graph.
- Graph Connectedness: Both DFS and BFS can help determine if all vertices in a directed graph are connected.
- Bidirectional Search: Rather than using DFS or BFS alone, a bidirectional approach might search from both the start and target vertices to meet in the middle, optimizing search time.
- Iterative Deepening: This combines DFS's space efficiency and BFS's completeness, especially useful in scenarios like AI pathfinding.

