Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

Depth-First Traversal and Breadth-First Traversal #259

Open Qingquan-Li opened 9 months ago

Qingquan-Li commented 9 months ago

Example Graph

Consider the following graph, which we'll use for demonstrating DFS and BFS:

    1
   / \
  2   3
 /   / \
4   5   6

Depth-First Traversal (DFS)

DFS explores as far as possible down one path before backtracking.

DFS Steps:

  1. Start at node 1.
  2. Visit node 2.
  3. Visit node 4, the child of node 2. (No more children, backtrack to node 2, then to node 1)
  4. Visit node 3.
  5. Visit node 5, the child of node 3.
  6. Visit node 6, the other child of node 3.

DFS Traversal Order: 1, 2, 4, 3, 5, 6

Breadth-First Traversal (BFS)

BFS explores the neighbor nodes first before going to the next level of nodes.

BFS Steps:

  1. Start at node 1.
  2. Visit nodes 2 and 3, the neighbors of node 1.
  3. Visit node 4, the child of node 2.
  4. Visit nodes 5 and 6, the children of node 3.

BFS Traversal Order: 1, 2, 3, 4, 5, 6

Visualization in Graph Form

These examples demonstrate how DFS explores as deeply as possible into each branch before backtracking, while BFS explores all neighbors at the current depth level before moving to the next level. DFS is often implemented using recursion or a stack, while BFS is typically implemented using a queue.