What is DFS and When Is It Used?
Depth-First Search (DFS) is a graph traversal algorithm that starts from a source node and explores as far as possible along each branch before backtracking. It is commonly used for problems like connectivity checks, cycle detection, and solving puzzles such as mazes.
How DFS Works
When DFS is started from a node, it marks that node as visited and recursively (or using a stack) visits each of its unvisited neighbors. This continues until all possible paths from the starting node are fully explored.
Case 1: Fully Connected Graph
In a graph where every node is connected (directly or indirectly), DFS will eventually visit every node. This helps identify all components reachable from the source.
Case 2: Disconnected Graph
If the graph is disconnected, DFS from one node will not reach nodes in other disconnected components. To traverse all nodes in such cases, DFS should be applied to every unvisited node in the graph (often used in counting connected components).
Case 3: Graph with Cycles
DFS can handle cycles using a visited
set to avoid infinite loops. If a visited node is encountered again, DFS simply skips it.
Case 4: Directed vs. Undirected Graphs
DFS works similarly for both, but the direction of edges is respected. In a directed graph, DFS follows edges only in the given direction. In undirected graphs, it can traverse both directions.
Implementation Insight
DFS can be implemented recursively or using an explicit stack (for iterative approach). Both approaches use a visited
structure (set or array) to track explored nodes.