5 3 2 7 4 6 3 1 2 3 4 5 6 7 8

Graphs

Introduction · Representation · Traversal · Minimum Spanning Trees · Shortest Path Algorithms

Why Study Graphs?

Many real-world problems cannot be represented using arrays, linked lists, or trees alone. Graphs model arbitrary relationships between entities.

Road Maps
Social Networks
Internet
Computer Networks
Flight Routes
Electrical Networks
Dependency Graphs
Knowledge Graphs
180 km 120 km 150 km 100 km 80 km 200 km 90 km 250 km 350 km 200 km Pokhara Chitwan Nepalgunj Butwal Kathmandu Biratnagar
“Graphs model relationships rather than hierarchy.”

6.1 Introduction

What is a Graph?

A graph is a non-linear data structure consisting of a set of vertices (nodes) and a set of edges connecting pairs of vertices.

\[ G = (V, E) \]

V = Set of Vertices  ·  E = Set of Edges

V = {A, B, C, D, E}
E = {(A,B), (A,C), (B,D), (C,D), (D,E)}

  • Graph may be directed or undirected
  • Graph may contain cycles
  • Graph may be connected or disconnected
  • Graph can represent many-to-many relationships
A B C D E
\[ G = (V, E) \]
“Graphs model relationships instead of parent-child hierarchy.”

Building a Graph

1

Create vertices. Start with isolated nodes — no connections yet.

2

Connect vertices using edges to form relationships.

3

Assign weights (optional) — e.g., distance, cost, or capacity.

4

Assign directions (optional) — edges may be one-way or two-way.

Important Note
  • A graph does not require a root node.
  • A graph may contain cycles.
  • A graph can have multiple paths between nodes.
A B C D E F ⚠ Cycle Detected
Connected Disconnected Directed Undirected Weighted Unweighted

6.1.2 Graph Terminologies (Part 1)

Basic Components of a Graph

Vertex (Node)

A point representing an object or entity in the graph.

Edge

A connection or relationship between two vertices.

Adjacent Vertices

Two vertices connected directly by a single edge.

Incident Edge

An edge connected to a particular vertex.

A B C D E A A B 3 incident edges →
Vertex Edge Adjacency Incidence

Graph Terminologies (Part 2)

Degree of a Vertex

Degree of a vertex is the number of edges connected to it.

\[ \deg(v) = \text{number of edges incident on } v \]

In-degree of a vertex in a directed graph: number of edges coming into the vertex.

\[ \text{in-deg}(v) = \text{incoming edges to } v \]

Out-degree of a vertex in a directed graph: number of edges going out of the vertex.

\[ \text{out-deg}(v) = \text{outgoing edges from } v \]
Undirected Graph A B C D A deg(A)=3 B deg(B)=2 C deg(C)=2 D deg(D)=3 Directed Graph P Q R S in=1 in=1 in=1 in=2 out=2 out=1 out=1 out=1
\[ \sum_{v \in V} \deg(v) = 2 \times |E| \quad\text{(Total degree = 2 × number of edges)} \]

6.2 Types of Graphs

Directed Graph vs Undirected Graph — the fundamental distinction

Undirected Graph

Edges have no direction. The relationship is bidirectional — if A connects to B, then B connects to A.

  • Examples: Facebook Friendship, Roads, Electric Connections
  • Advantages: Simple, Easy traversal
  • Applications: Networks, Maps

Directed Graph

Every edge has a direction, represented using arrows. A → B does not imply B → A.

  • Examples: Instagram Follow, Twitter Follow, One-way Roads, Task Scheduling
  • Applications: Dependency Graphs, Compiler, Workflow
Undirected Graph A B C D E (A,B) (A,C) (B,D) (C,D) (D,E) Path: A↔B↔D Directed Graph A B C D E A→B A→C B→D C→D D→E out(A) = 2 in(D) = 2 Arrows show direction of relationship
Feature Undirected Directed
Direction No direction — edges are symmetric Directional — edges have arrows
Traversal Bidirectional: A↔B both ways One-way: A→B only (unless B→A exists)
Applications Social networks, road maps, electrical grids Web links, task scheduling, compilers
Representation Symmetric adjacency matrix Asymmetric adjacency matrix
Example Facebook friendship (mutual) Twitter follow (one-way)

Weighted Graph vs Unweighted Graph

Adding numerical values to edges — cost, distance, or capacity

5

Weighted Graph

Edges contain numerical values. Weights may represent:

  • Distance, Cost, Time
  • Bandwidth, Latency

Examples: Google Maps, Flight Routes, Computer Networks

Unweighted Graph

Every edge is treated equally. Only the structure (who connects to whom) matters — no cost or distance associated.

Examples: Friendship Graph, Website Links, Hierarchy

Weighted Graph 150 220 180 95 110 KTM PKR BRT BTL CTN Unweighted Graph KTM PKR BRT BTL CTN All edges have equal cost
Aspect Weighted Unweighted
Storage Adjacency matrix stores weight values Adjacency matrix stores 0/1 only
Search Dijkstra's / Bellman-Ford (weight-based) BFS — each edge has equal cost
Shortest Path Minimum total weight along path Fewest number of edges (hops)
Applications GPS navigation, network routing, logistics Social networks, web crawling, hierarchies
D

Cyclic Graph vs Acyclic Graph

Does a closed loop exist?

Cycle

A path that starts and ends at the same vertex.

Example: A → B → C → A

Cyclic Graph

A graph that contains at least one cycle.

May also contain non-cycle parts.

Acyclic Graph

A graph with no cycles at all.

DAGs are directed acyclic graphs — common in task scheduling.

🌳

Tree = Acyclic + Connected

Every tree is acyclic, but not every acyclic graph is a tree (could be a forest).

Cyclic Graph
Cycle: A → B → C → A A B C 1 1
Acyclic Graph (Tree)
No Cycle A B C D 1 1 1
Cyclic Graph Acyclic Graph
Definition Contains at least one cycle No cycles exist
Key Property Path loops back to start All paths are finite
Example Friendship circle (mutual friends) Project task dependencies (DAG)
E

Connected Graph vs Disconnected Graph

Can you reach every vertex?

Connected Graph

A graph where every pair of vertices has a path between them.

Removing any single edge does NOT necessarily disconnect it.

Analogy: A road network where every town is reachable from every other town.

Disconnected Graph

A graph where at least one pair of vertices has no path between them.

Contains two or more connected components.

Analogy: An airline network where not all cities have direct or indirect flights to each other.

Connected Component

A maximal connected subgraph — the largest group of vertices that are all reachable from each other.

Every disconnected graph can be decomposed into its connected components.

Use: Social network analysis — friend circles as components.

Connected Graph
1 1 1 1 1 1 1 A B C D E F
Disconnected Graph
Component 1 Component 2 1 1 1 1 1 1 1 1 1 A B C D E F G H I
Key Insight: A connected graph has exactly 1 component. A disconnected graph with k components requires k BFS/DFS calls to visit all vertices.
F

Why Do We Need Graph Representation?

From drawing to data structure

Adjacency Matrix

A V × V 2D array where Matrix[i][j] = 1 if edge (i, j) exists.

Advantage: O(1) edge lookup  |  Disadvantage: O(V²) space

Incidence Matrix

A V × E matrix where row = vertex, column = edge. Entry is 1 if vertex is an endpoint of that edge.

Advantage: Captures edge identity  |  Disadvantage: Sparse, O(V × E) space

Adjacency List

Each vertex stores a list of its neighbors. Space-efficient for sparse graphs.

Advantage: O(V + E) space  |  Disadvantage: Edge lookup O(degree)

Graph 1 1 1 1 1 A B C D E store Matrix A B C D E A B C D E or List A → B, C B → A, D C → A, D D → B, C, E E → D
Graph
Representation
Algorithms
Applications
G

Adjacency Matrix

V × V matrix — constant-time edge lookup

Definition

An Adjacency Matrix is a V × V matrix where:

Matrix[i][j] = 1  if edge (i, j) exists
Matrix[i][j] = 0  otherwise

Rows & Columns

Both rows and columns represent vertices, listed in order A, B, C, D, E.

Symmetric Property

For undirected graphs, Matrix[i][j] = Matrix[j][i]. The matrix is symmetric about the diagonal.

Directed Difference

For directed graphs, Matrix[i][j] ≠ Matrix[j][i] in general — direction matters.

A B C C D E A B C C D E
A B C D E
A 0 1 1 0 0
B 1 0 0 1 0
C 1 0 0 1 0
D 0 1 1 0 1
E 0 0 0 1 0
↕  Matrix is symmetric — undirected graph
Space
O(V²)
Edge Lookup
O(1)
Insert Edge
O(1)
Traversal
O(V²)
H

Incidence Matrix

V × E matrix — one column per edge

Definition

An Incidence Matrix is a V × E matrix:

Rows = vertices  (A, B, C, D)
Columns = edges  (e1, e2, e3, e4)

Undirected Graph

Each column has exactly two 1's — the endpoints of that edge.

Column for edge (A, B): row A = 1, row B = 1, all others = 0

Directed Graph

Each column has one +1 (tail) and one −1 (head).

Edge A→B: row A = +1, row B = −1

e1 e2 e3 e4 A B C D
e1 e2 e3 e4
A 1 1 0 0
B 1 0 1 0
C 0 1 0 1
D 0 0 1 1
Easy edge tracking — each edge is a column
Ideal for edge-based algorithms (e.g. Eulerian circuits)
I

Adjacency Matrix vs Incidence Matrix

Choosing the right representation

Criteria ▦ Adjacency Matrix ⊞ Incidence Matrix
📐 Rows V (vertices) V (vertices)
📊 Columns V (vertices) E (edges)
💾 Memory O(V²) — wasteful for sparse O(V × E) — better for sparse
🔍 Edge Search O(1) O(E)
🔄 Traversal O(V²) O(V × E)
Insert Edge O(1) O(V)
🗑️ Delete Edge O(1) O(V)
🎯 Best For Dense graphs, fast lookup Edge-centric algorithms, circuits
Which representation should you choose?
Need fast edge lookup?
▦ Adjacency Matrix
Need edge-level information?
⊞ Incidence Matrix
J

Adjacency List Representation

Array of lists — the most common choice

Definition

An Adjacency List stores every vertex together with a list of all its adjacent vertices.

How It Works
  • One list is maintained for each vertex
  • Every list stores neighboring vertices
  • Space efficient for sparse graphs
Advantages
  • Requires less memory — O(V + E)
  • Easy graph traversal
  • Efficient insertion of edges
  • Most widely used representation
A B C D E
A
B
C
B
A
D
C
A
D
D
B
C
E
E
D
Space
O(V + E)
Edge Lookup
O(degree)
Traversal
O(V + E)
K

Comparison of Graph Representations

Which one should you choose?

Criteria ▦ Adjacency Matrix ⊞ Incidence Matrix ≡ Adjacency List
Rows V V V
Columns / Structure V (full matrix) E (full matrix) Each row = neighbor list
Memory Usage O(V²) O(V × E) O(V + E)
Edge Lookup O(1) O(E) O(degree)
Traversal O(V²) O(V × E) O(V + E)
Insert Edge O(1) O(V) O(1)
Delete Edge O(1) O(V) O(degree)
Sparse Graphs Wasteful OK Ideal
Dense Graphs Ideal Verbose Good
Implementation Simple Moderate Simple
Need fast edge lookup?
▦ Adjacency Matrix
Need memory efficiency?
≡ Adjacency List
Need edge-oriented algorithms?
⊞ Incidence Matrix
Most modern graph algorithms use the Adjacency List representation.
L

Basic Graph Operations

Adding, removing, and searching

+

Add Vertex

Insert a new vertex into the graph.

Remove Vertex

Delete vertex and all its incident edges.

Add Edge

Connect two existing vertices.

Remove Edge

Delete a specific edge between vertices.

1 1 1 A B C D E new 1 1 B
👥 Social Networks
🗺️ GPS Navigation
🌐 Network Topology
📦 Dependency Graphs
M

Graph Operations using Adjacency List

Pseudocode + live update

AddVertex(v)
function AddVertex(v):
  adjList[v] ← empty list
AddEdge(u, v)
function AddEdge(u, v):
  adjList[u].append(v)
  adjList[v].append(u) // undirected
RemoveEdge(u, v)
function RemoveEdge(u, v):
  adjList[u].remove(v)
  adjList[v].remove(u)
RemoveVertex(v)
function RemoveVertex(v):
  for each u ∈ adjList[v]:
    adjList[u].remove(v)
  adjList.remove(v)
SearchVertex(v) / SearchEdge(u,v)
function SearchEdge(u, v):
  return v ∈ adjList[u]
A
B
C
B
A
D
C
A
D
B
E
Add Vertex
O(1)
Add Edge
O(1)
Search Edge
O(degree)
Delete Edge
O(degree)
Delete Vertex
O(V + E)
N

Graph Traversal

Depth-First Search (DFS) and Breadth-First Search (BFS)

D

Depth-First Search

Uses Stack — goes as deep as possible before backtracking.

Implemented via Recursion or explicit Stack.

Maze Solving Topological Sort Cycle Detection Connected Components
B

Breadth-First Search

Uses Queue — visits level by level, exploring all neighbors first.

Guarantees shortest path in unweighted graphs.

Shortest Path Broadcasting Social Networks GPS Navigation
1 1 1 1 1 1 1 A B C D E F G
DFS → Stack
BFS → Queue
O

Depth-First Search (DFS)

Explore deep before wide — stack-based traversal

Definition

DFS explores one branch completely before backtracking. It visits a vertex, marks it, then recursively visits each unvisited neighbor.

Pseudocode
function DFS(v):
  mark v as visited
  visit(v)
  for each neighbour of v:
    if neighbour not visited:
      DFS(neighbour)
Time
O(V + E)
Space
O(V)
A B C D E F G
Stack
A
B
D
G
F
C
Traversal Order: A → B → D → E → G → F → C
P

Breadth-First Search (BFS)

Level-by-level traversal — queue-based

Definition

BFS visits vertices level by level. It explores all neighbors at the current depth before moving to the next level.

Uses a Queue (FIFO).

Pseudocode
function BFS(start):
  enqueue(start)
  while queue not empty:
    v ← queue.removeFront()
    if v not visited:
      visit(v)
      for each n in neighbours(v):
        enqueue(n)
Time
O(V + E)
Space
O(V)
A B C D E F G
Queue
A
B, C
C, D, E
D, E, F
E, F
F, G
G
Traversal Order: A → B → C → D → E → F → G
Q

DFS vs BFS

Choosing the right traversal strategy

Criteria Depth-First Search (DFS) Breadth-First Search (BFS)
Data Structure Stack (or Recursion) Queue
Traversal Style Deep — goes as far as possible Wide — visits all neighbors first
Memory O(V) — path depth O(V) — level width
Shortest Path No guarantee Yes (unweighted)
Recursion Natural fit Not used
Applications Maze, Topo Sort, Cycle Detection Shortest Path, GPS, Social Networks
Traversal Order A → B → D → E → G → F → C A → B → C → D → E → F → G
Time Complexity O(V + E) O(V + E)
DFS — Tree-like
A B D E G F C
BFS — Level-by-Level
A B C D E F G
DFS
✓ Deep Exploration
✓ Stack
✓ Backtracking
BFS
✓ Level Order
✓ Queue
✓ Shortest Path (Unweighted)