Graph Traversal Techniques

Depth First Search (DFS) Example

  • Graph Structure

    • Discussed undirected graph containing 5 vertices.

    • Visual representation includes vertices labeled 0, 1, 2, 3, and 4.

  • DFS Algorithm Workflow

    • Step 1: Initialization

    • Start from vertex 0.

    • Add vertex 0 to the Visited list.

    • Push all adjacent vertices of 0 onto the Stack.

  • Step 2: Visiting Nodes

    • Visit the top element of the Stack, which is now 1.

    • Check adjacent nodes of 1:

    • Since 0 has already been visited, move to visit 2.

    • Add 2 to the Visited list.

  • Step 3: Continuing the Traversal

    • Continue visiting from vertex 1, now looking at adjacent nodes.

    • Since 0 is visited, proceed to visit 2:

    • Reiterate action for clarity, confirming addition of 2 to the Visited.

  • Step 4: Exploring Further

    • Vertex 2 has an unvisited adjacent vertex, which is 4.

    • Add 4 to the top of the stack.

    • Visit 4.

  • Step 5: Final Node Visits

    • Conclude traversal after visiting vertex 3:

    • No unvisited adjacent nodes remain, therefore, Depth First Traversal is complete.

Breadth First Search (BFS) Algorithm

  • Graph Structure

    • The same undirected graph of 5 vertices is used:

    • Layout: vertices labeled 0, 1, 2, 3, and 4.

  • BFS Algorithm Workflow

    • Step 1: Initialization

    • Start from vertex 0.

    • Add vertex 0 to the Visited list.

    • Place all adjacent vertices of 0 into the Queue.

  • Step 2: Processing the Queue

    • Access the front of the Queue, starting with vertex 1.

    • Examine adjacent nodes of 1:

    • As 0 is visited, proceed to visit neighbor 2 instead.

    • Visited the first neighbor associated with start node 0 (which is 1).

  • Step 3: Continue Traversal

    • Vertex 2 is now in focus due to queue order.

    • Check adjacent nodes and add unvisited vertex 4 to the back of the queue.

    • Proceed to visit 3, which is currently at the front of the queue.

  • Step 4: Final Visits

    • Continue examining the remaining queue:

    • Vertex 3 has already visited 0 (only adjacent node).

    • Visit the last item in the queue, 4.

    • With no unvisited neighbors remaining after 4, and the queue being empty, Breadth First Traversal concludes.