MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Graph Theory: Adjacency Matrix vs List & BFS vs DFS Traversals0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
8.1Graph Theory: Adjacency Matrix vs List & BFS vs DFS Traversals8.2Cycle Detection & Topological Sorting (Kahn's BFS & DFS)8.3Shortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted8.4Dynamic Programming: Overlapping Subproblems, Memoization vs Tabulation8.5Classic DP Master Patterns: 0/1 Knapsack, Coin Change & LCS
HomeTutorialsData Structures & AlgorithmsGraph Theory: Adjacency Matrix vs List & BFS vs DFS Traversals
Cycle Detection & Topological Sorting (Kahn's BFS & DFS)

Graph Theory: Adjacency Matrix vs List & BFS vs DFS Traversals

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

A Graph is a non-linear data structure consisting of a finite set of vertices (or nodes) $V$ and a collection of edges $E$ that connect pairs of vertices: $G = (V, E)$. Graphs generalize trees by eliminating the constraints of root nodes, parent-child hierarchies, and cycle-free requirements. Graphs model networks everywhere: social networks (friendships), city road systems, internet web pages (hyperlinks), and dependency packaging systems.

Graph Representations and TraversalsClick to Zoom
Graph Representations and Traversals

1. Graph Classifications & Terminology

Before writing code, we categorize graphs according to direction, weighting, and cyclic nature:

  1. 1
    Directed (Digraph) vs. Undirected:
  • Undirected: If an edge exists between node $A$ and node $B$, you can travel bidirectionally: $(A, B) = (B, A)$.
  • Directed: Edges have orientation (arrows). $(A \to B)$ allows movement only from $A$ to $B$.
  1. 1
    Weighted vs. Unweighted:
  • Unweighted: Every edge has uniform cost (effectively $1$).
  • Weighted: Edges carry numerical values representing distance, latency, toll fee, or capacity.
  1. 1
    Cyclic vs. Acyclic:
  • Cyclic: Contains at least one closed walk starting and ending at the same vertex.
  • Acyclic (DAG): Directed Acyclic Graph contains zero directed cycles (essential for scheduling, Git commits, and compilers).
  1. 1
    Degree:
  • In undirected graphs, degree is the number of incident edges.
  • In directed graphs, In-Degree is the count of incoming edges; Out-Degree is the count of outgoing edges.

2. Graph Representations: Matrix vs. List

1Graph:
2 (0) ----- (1)
3 | / |
4 | / |
5 | / |
6 (2) ----- (3)
7 
81. Adjacency Matrix (4x4 Grid):
9 0 1 2 3
10 0 [0, 1, 1, 0]
11 1 [1, 0, 1, 1]
12 2 [1, 1, 0, 1]
13 3 [0, 1, 1, 0]
14 Space: O(V^2)
15 
162. Adjacency List (Hash Map or Array of Lists):
17 0: [1, 2]
18 1: [0, 2, 3]
19 2: [0, 1, 3]
20 3: [1, 2]
21 Space: O(V + E)

Representation Trade-Off Matrix

Operation / MetricAdjacency MatrixAdjacency List (Standard)Winner
Space Complexity$O(V^2)$ regardless of edge count$O(V + E)$ (or $O(V + 2E)$ for undirected)List for sparse graphs
Add Vertex$O(V^2)$ (reallocate matrix)$O(1)$List
Add Edge$O(1)$$O(1)$Tie
Query Edge (u, v)$O(1)$ (matrix[u][v] == 1)$O(\text{deg}(u))$ (search list)Matrix
Iterate Neighbors of u$O(V)$ (scan entire row)$O(\text{deg}(u))$ (scan only actual neighbors)List

In technical interviews and real-world software, graphs are overwhelmingly sparse ($E \ll V^2$), making the Adjacency List the universal industry choice.


3. Graph Traversal: BFS vs. DFS

Traversing a graph requires exploring all reachable vertices while maintaining a visited set to prevent infinite loops caused by cycles.

Breadth-First Search (BFS)

  • Data Structure: FIFO Queue (collections.deque).
  • Strategy: Layer-by-layer exploration (level order).
  • Core Property: Computes the shortest path in unweighted graphs (minimum edge count).

Depth-First Search (DFS)

  • Data Structure: LIFO Stack (or recursion call stack).
  • Strategy: Explore as deep as possible along each branch before backtracking.
  • Core Property: Natural for connectivity, maze solving, cycle detection, and topological sorting.

4. Step-by-Step Traversal Trace

Given an undirected graph with nodes 0, 1, 2, 3, 4 and edges: (0,1), (0,2), (1,3), (2,4). Starting at node 0:

BFS Step-by-Step Execution

StepCurrent NodeVisited SetQueue State (Front -> Back)Action / Neighbors Added
Initial-{0}[0]Start at root 0
10{0, 1, 2}[1, 2]Dequeue 0, add neighbors 1, 2
21{0, 1, 2, 3}[2, 3]Dequeue 1, add neighbor 3
32{0, 1, 2, 3, 4}[3, 4]Dequeue 2, add neighbor 4
43{0, 1, 2, 3, 4}[4]Dequeue 3, no unvisited neighbors
54{0, 1, 2, 3, 4}[]Dequeue 4, no unvisited neighbors. Queue empty!

BFS Traversal Order: [0, 1, 2, 3, 4]


5. Dual-Language Implementation

Python 3 Implementation

1from collections import deque, defaultdict
2from typing import List, Dict, Set
3 
4class Graph:
5 def __init__(self, is_directed: bool = False):
6 self.adj_list: Dict[int, List[int]] = defaultdict(list)
7 self.is_directed = is_directed
8 
9 def add_edge(self, u: int, v: int) -> None:
10 self.adj_list[u].append(v)
11 if not self.is_directed:
12 self.adj_list[v].append(u)
13 
14 def bfs(self, start: int) -> List[int]:
15 # Layer-by-layer exploration using an explicit FIFO Queue
16 visited: Set[int] = {start}
17 queue: deque[int] = deque([start])
18 traversal: List[int] = []
19 
20 while queue:
21 node = queue.popleft()
22 traversal.append(node)
23 
24 for neighbor in self.adj_list[node]:
25 if neighbor not in visited:
26 visited.add(neighbor)
27 queue.append(neighbor)
28 
29 return traversal
30 
31 def dfs(self, start: int) -> List[int]:
32 # Deep exploration using recursion (implicit call stack)
33 visited: Set[int] = set()
34 traversal: List[int] = []
35 
36 def _dfs_helper(node: int) -> None:
37 visited.add(node)
38 traversal.append(node)
39 for neighbor in self.adj_list[node]:
40 if neighbor not in visited:
41 _dfs_helper(neighbor)
42 
43 _dfs_helper(start)
44 return traversal
45 
46# Example Usage
47if __name__ == "__main__":
48 g = Graph(is_directed=False)
49 edges = [(0, 1), (0, 2), (1, 3), (2, 4)]
50 for u, v in edges:
51 g.add_edge(u, v)
52 
53 print("BFS Order:", g.bfs(0)) # [0, 1, 2, 3, 4]
54 print("DFS Order:", g.dfs(0)) # [0, 1, 3, 2, 4]

Modern JavaScript (Node.js / ES6) Implementation

1class Graph {
2 constructor(isDirected = false) {
3 this.adjList = new Map();
4 this.isDirected = isDirected;
5 }
6 
7 addVertex(v) {
8 if (!this.adjList.has(v)) {
9 this.adjList.set(v, []);
10 }
11 }
12 
13 addEdge(u, v) {
14 this.addVertex(u);
15 this.addVertex(v);
16 this.adjList.get(u).push(v);
17 if (!this.isDirected) {
18 this.adjList.get(v).push(u);
19 }
20 }
21 
22 bfs(start) {
23 const visited = new Set([start]);
24 const queue = [start];
25 const order = [];
26 
27 while (queue.length > 0) {
28 const node = queue.shift();
29 order.push(node);
30 
31 const neighbors = this.adjList.get(node) || [];
32 for (const neighbor of neighbors) {
33 if (!visited.has(neighbor)) {
34 visited.add(neighbor);
35 queue.push(neighbor);
36 }
37 }
38 }
39 return order;
40 }
41 
42 dfs(start) {
43 const visited = new Set();
44 const order = [];
45 
46 const dfsRecursive = (node) => {
47 visited.add(node);
48 order.push(node);
49 
50 const neighbors = this.adjList.get(node) || [];
51 for (const neighbor of neighbors) {
52 if (!visited.has(neighbor)) {
53 dfsRecursive(neighbor);
54 }
55 }
56 };
57 
58 dfsRecursive(start);
59 return order;
60 }
61}
62 
63// Example Execution
64const g = new Graph(false);
65[[0, 1], [0, 2], [1, 3], [2, 4]].forEach(([u, v]) => g.addEdge(u, v));
66 
67console.log("BFS Order:", g.bfs(0)); // [0, 1, 2, 3, 4]
68console.log("DFS Order:", g.dfs(0)); // [0, 1, 3, 2, 4]

6. Complexity Analysis

AlgorithmTime ComplexitySpace ComplexityPrimary Best-Use Case
BFS (Adj List)$O(V + E)$$O(V)$Finding unweighted shortest path; finding nodes within $k$ hops
DFS (Adj List)$O(V + E)$$O(V)$ (recursion depth)Topological sort; backtracking; finding cycles; flood fill
BFS (Adj Matrix)$O(V^2)$$O(V)$Dense graphs where $E \approx V^2$

Why $O(V + E)$? Every vertex is placed into the queue/stack at most once ($O(V)$). For each vertex, we iterate over all its incident edges ($O(E)$ total edges processed across all adjacency lists).


7. Common Pitfalls & Interview Traps

  1. 1
    Disconnected Graphs / Forest: Calling BFS or DFS from a single starting node only visits that connected component. In problems like Number of Connected Components or Number of Islands, you must wrap BFS/DFS in an outer loop over all vertices: for node in range(V): if node not in visited: bfs(node).
  2. 2
    Missing visited Check before Queueing: Adding nodes to the BFS queue without marking them visited immediately allows duplicates into the queue, causing catastrophic $O(2^V)$ exponential memory spikes!
  3. 3
    Call Stack Overflow in DFS: Deep graph traversals (e.g., $10^5$ linear nodes) will crash Python with RecursionError. In production or deep graphs, convert DFS to an explicit stack loop.

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What is the primary advantage of representing a sparse graph using an Adjacency List instead of an Adjacency Matrix?
Question 2
Why is Breadth-First Search (BFS) guaranteed to find the shortest path between two nodes in an unweighted graph?
Question 3
If a graph has 10,000 vertices and 12,000 edges, what is the space complexity of an Adjacency Matrix vs. an Adjacency List?
Question 4
When implementing BFS on a graph, at which precise moment MUST a node be marked as visited?
Question 5
What is the time complexity of running Depth-First Search on a graph with $V$ vertices and $E$ edges represented by an adjacency list?

Next Lesson

Cycle Detection & Topological Sorting (Kahn's BFS & DFS)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Heaps & Priority Queues: Min-Heap, Max-Heap, Heapify & Top-K ElementsCycle Detection & Topological Sorting (Kahn's BFS & DFS)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext