Skip to main content

Depth First Search (DFS) (Geeks for Geeks)

1. What is Depth First Search (DFS)?​

Depth First Search (DFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the root (or an arbitrary node in the graph) and explores as far as possible along each branch before backtracking.

2. Algorithm for Depth First Search (DFS)​

  1. Start with the root node (or an arbitrary node in the graph).
  2. Mark the node as visited.
  3. For each adjacent node, recursively apply the DFS algorithm if the node has not been visited.

3. How does Depth First Search (DFS) work?​

  • DFS explores as far as possible along each branch before backtracking.
  • It uses a stack data structure, either implicitly through recursion or explicitly through an iterative approach.
  • Nodes are marked as visited to prevent reprocessing.

4. Problem Description​

Given a graph represented as an adjacency list, implement the Depth First Search (DFS) algorithm to traverse the graph starting from a given source node.

5. Examples​

Example 1:

Input:
graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [3]
}
start_node = 2
Output: 2 0 1 3

Example 2:

Input:
graph = {
0: [1, 3],
1: [0, 2],
2: [1, 3],
3: [0, 2]
}
start_node = 0
Output: 0 1 2 3

6. Constraints​

  • Thegraphcanhaveanynumberofnodes.The graph can have any number of nodes.
  • Thegraphcanbedirectedorundirected.The graph can be directed or undirected.

7. Implementation​

Written by @ngmuraqrdd
def dfs(graph, start_node, visited=None):
if visited is None:
visited = set()
visited.add(start_node)
result = [start_node]
for neighbor in graph[start_node]:
if neighbor not in visited:
result.extend(dfs(graph, neighbor, visited))
return result

# Example usage:
graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [3]
}
start_node = 2
print(dfs(graph, start_node))

8. Complexity Analysis​

  • Time Complexity: O(V+E)O(V + E), where VV is the number of vertices and EE is the number of edges. Each vertex and edge is processed once.
  • Space Complexity: O(V)O(V), where VV is the number of vertices. This is for the visited set and the recursive stack space.

9. Advantages and Disadvantages​

Advantages:

  • Can be easily implemented with recursion.
  • Useful for problems that involve exploring all paths, like puzzles and mazes.

Disadvantages:

  • Can be memory intensive due to the stack space in recursion.
  • Not optimal for finding the shortest path in unweighted graphs.

10. References​