DSA Graphs Implementation

DSA Tutorial

DSA Graphs Implementation – Complete Practical Guide

(Adjacency Matrix • Adjacency List • BFS • DFS • Code • Complexity)

Implementing Graphs is a core DSA skill.
In exams & interviews, you are mainly expected to know two representations and two traversals.


1️⃣ Graph Implementation Methods

Graphs are implemented in two main ways:

  1. Adjacency Matrix

  2. Adjacency List (Most used)


2️⃣ Adjacency Matrix Implementation

Concept

  • Use a 2D array

  • matrix[i][j] = 1 → edge exists

  • matrix[i][j] = 0 → no edge


 Example Graph

0 —— 1
| \ |
| \ |
2 —— 3

 Adjacency Matrix

0 1 2 3
0 0 1 1 1
1 1 0 0 1
2 1 0 0 1
3 1 1 1 0

 C++ Implementation


 


⏱ Complexity (Adjacency Matrix)

Metric Value
Space O(V²)
Edge check O(1)
Traversal O(V²)

3️⃣ Adjacency List Implementation (MOST IMPORTANT)

 Concept

  • Each vertex stores a list of neighbors

  • Uses vector / list


 Representation

0 → 1, 2, 3
1 → 0, 3
2 → 0, 3
3 → 0, 1, 2

 C++ Implementation


 


⏱ Complexity (Adjacency List)

Metric Value
Space O(V + E)
Traversal O(V + E)

4️⃣ BFS Implementation (Graph Traversal)

 Breadth First Search

  • Uses Queue

  • Level-by-level traversal


 BFS Code (C++)


 


5️⃣ DFS Implementation

 Depth First Search

  • Uses recursion / stack

  • Goes deep first


 DFS Code (C++)


 


6️⃣ Complete Graph + BFS + DFS Example


 


7️⃣ Directed Graph Implementation

For directed graph, add edge in one direction only:

adj[u].push_back(v); // u → v

8️⃣ Adjacency Matrix vs List

Feature Matrix List
Space O(V²) O(V+E)
Sparse Graph ❌ Bad ✅ Best
Dense Graph ✅ OK
Interview Use

Interview Questions (Graphs Implementation)

Q1. Which graph representation is most used?
👉 Adjacency List

Q2. BFS uses which data structure?
👉 Queue

Q3. DFS uses which data structure?
👉 Stack / Recursion

Q4. Time complexity of BFS/DFS?
👉 O(V + E)


Final Summary

✔ Graphs implemented using matrix or list
✔ Adjacency list is preferred
✔ BFS → Queue
✔ DFS → Stack / Recursion
✔ Core topic for DSA & interviews

You may also like...