DSA Graph Traversal

DSA Tutorial

DSA Graph Traversal – Complete Beginner Guide

(BFS • DFS • Algorithms • Examples • Code • Complexity)

Graph Traversal means visiting all vertices (nodes) of a graph systematically.
It is a foundation topic for almost every graph algorithm.


1️⃣ What is Graph Traversal?

Graph traversal is the process of:

  • Visiting each vertex exactly once

  • Avoiding infinite loops using a visited array

 Required because graphs may contain cycles.


2️⃣ Types of Graph Traversal

There are two main traversal algorithms:

  1. Breadth First Search (BFS)

  2. Depth First Search (DFS)

Both are very important for exams & interviews.


3️⃣ Breadth First Search (BFS)

 Concept

  • Visits nodes level by level

  • Uses a Queue

  • Explores all neighbors first

 Best for shortest path in unweighted graphs.


 BFS Algorithm (Steps)

  1. Start from a source node

  2. Mark it as visited

  3. Push it into a queue

  4. While queue is not empty:

    • Dequeue node

    • Visit all unvisited neighbors

    • Mark them visited and enqueue


 BFS Example

Graph:



 

Start from 0

BFS Order

0 1 2 3

 BFS Code (C++)


 


4️⃣ Depth First Search (DFS)

 Concept

  • Goes as deep as possible before backtracking

  • Uses Recursion or Stack

 Useful for cycle detection, topological sort.


 DFS Algorithm (Steps)

  1. Start from a node

  2. Mark it visited

  3. Visit an unvisited neighbor

  4. Repeat recursively

  5. Backtrack when no unvisited neighbors


 DFS Example

Graph:



 

Start from 0

DFS Order

0 1 3 2

(order may vary)


DFS Code (C++ – Recursive)


 


 DFS Code (Iterative – Stack)


 


5️⃣ BFS vs DFS

FeatureBFSDFS
Data StructureQueueStack / Recursion
TraversalLevel-wiseDepth-wise
Shortest Path✅ Yes❌ No
MemoryMoreLess
Use CaseUnweighted shortest pathCycle detection

6️⃣ Traversal of Disconnected Graph

If graph is disconnected, start traversal from each unvisited vertex:

 Very common interview question.


7️⃣ Time & Space Complexity

 Time Complexity

BFS = O(V + E)
DFS = O(V + E)

Space Complexity

  • BFS → O(V)

  • DFS → O(V)


8️⃣ Real-Life Applications

✔ Google Maps (path finding)
✔ Social networks
✔ Web crawling
✔ Network broadcasting
✔ AI & game maps


Interview Questions (Graph Traversal)

Q1. Which traversal uses queue?
👉 BFS

Q2. Which traversal uses recursion?
👉 DFS

Q3. BFS or DFS for shortest path?
👉 BFS

Q4. Why visited array is needed?
👉 To avoid infinite loops


Final Summary

✔ Graph traversal visits all vertices
✔ Two main methods: BFS & DFS
✔ BFS → Queue, DFS → Stack
✔ Both run in O(V + E)
✔ Foundation for all graph algorithms

You may also like...