9 Graphs And Graph Algorithms

Data Structures and Algorithms · Unit 9

Graphs and Graph Algorithms

Exam-focused notes for Graphs and Graph Algorithms (Data Structures and Algorithms, BIT201): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.

Graphs and Graph Algorithms in short

A graph models things and the links between them, such as cities and roads, or people and friendships. Graph algorithms find routes, check connections and build cheap networks.

Graphs and Graph Algorithms: notes

Graph definition and types

A graph $G = (V, E)$ is a set of vertices (nodes) $V$ and a set of edges $E$ that join pairs of vertices.

Types of graphs:

  • Undirected graph: edges have no direction. An edge A-B is the same as B-A.
  • Directed graph (digraph): each edge has a direction, from one vertex to another.
  • Weighted graph: each edge has a number, called weight or cost, such as distance.
  • Unweighted graph: edges have no weight.
  • Connected graph: there is a path between every pair of vertices.
  • Cyclic graph: it has at least one cycle. An acyclic graph has none.
  • Complete graph: every pair of vertices is joined by an edge.

Terms: the degree of a vertex is the number of edges at it. A path is a sequence of vertices joined by edges. A cycle is a path that starts and ends at the same vertex.

An undirected graph with $n$ vertices has at most $n(n-1)/2$ edges.

Graph representation using adjacency matrix

An adjacency matrix is an $n \times n$ table. The entry $M[i][j]$ is 1 if there is an edge from vertex $i$ to vertex $j$, and 0 if not. For a weighted graph, we store the weight instead of 1.

Take the undirected graph with edges A-B, A-C, B-D, B-E, C-F, E-F.

ABCDEF
A011000
B100110
C100001
D010000
E010001
F001010
int adj[6][6] = {0};
void addEdge(int u, int v) {
    adj[u][v] = 1;
    adj[v][u] = 1;     // remove this line for a directed graph
}

Properties:

  • The matrix of an undirected graph is symmetric.
  • The space needed is $O(n^2)$, even for few edges.
  • Checking if an edge exists takes $O(1)$ time.
  • Finding all neighbours of a vertex takes $O(n)$ time.

An adjacency list is the other common way. Each vertex keeps a list of its neighbours. It uses $O(n + e)$ space and suits graphs with few edges.

Graph traversal definition

Graph traversal means visiting every vertex reachable from a start vertex exactly once. Because graphs can have cycles, we mark each vertex as visited so that it is not processed twice.

There are two main methods:

  • Breadth first search (BFS), which uses a queue.
  • Depth first search (DFS), which uses a stack or recursion.

Breadth first search (BFS) algorithm

BFS visits the start vertex, then all its neighbours, then the neighbours of those, and so on. It moves level by level.

  • Mark the start vertex visited and enqueue it.
  • While the queue is not empty, dequeue a vertex and process it.
  • Enqueue every unvisited neighbour and mark it visited.
void bfs(int start, int n) {
    int visited[10] = {0}, queue[10], front = 0, rear = 0;
    visited[start] = 1;
    queue[rear++] = start;
    while (front < rear) {
        int u = queue[front++];
        printf("%d ", u);
        for (int v = 0; v < n; v++)
            if (adj[u][v] && !visited[v]) {
                visited[v] = 1;
                queue[rear++] = v;
            }
    }
}

With an adjacency matrix BFS takes $O(n^2)$ time. With adjacency lists it takes $O(n + e)$. BFS also finds the shortest path in an unweighted graph, counted in edges.

What this unit covers

  • Graph definition and types
  • Graph representation using adjacency matrix
  • Graph traversal definition
  • Breadth first search (BFS) algorithm
  • Depth first search (DFS) algorithm
  • BFS and DFS tracing with examples
  • Shortest path problem definition
  • Dijkstra's algorithm for shortest path
  • Spanning tree definition
  • Minimum spanning tree (MST) definition
  • Prim's algorithm for MST
  • Round Robin algorithm for MST

BFS and DFS tracing with examples

2082 · 5 marks

Traverse the following graph using BFS and DFS. [5]

Show solved answer

BFS and DFS Graph Traversal

Given

The question asks to traverse a graph using BFS and DFS, but the actual graph (the figure/diagram) is not included in the text provided. No adjacency list, adjacency matrix, edge set, or vertex set is given.

Missing data: The specific graph (vertices and edges) required to perform the traversal is not available. Without it, the exact traversal orders cannot be determined, since traversal output depends entirely on the graph structure and the chosen starting vertex.

Because the graph is unreadable/absent, I will present the methodology and demonstrate it on a clearly labelled representative example, while flagging that the numeric traversal order is example-dependent and not the "official" answer to the missing figure.


Solution

Example Graph

      1
     / \
    2   3
   / \    \
  4   5    6

Adjacency list:

  • $1 \to 2, 3$
  • $2 \to 4, 5$
  • $3 \to 6$
  • $4 \to$ (none)
  • $5 \to$ (none)
  • $6 \to$ (none)

Breadth First Search (BFS)

Idea: Use a Queue (FIFO); visit level by level.

StepQueue (front→back)VisitedAction
1[1]{1}Start at 1
2[2, 3]{1,2,3}Dequeue 1, enqueue 2,3
3[3, 4, 5]{1,2,3,4,5}Dequeue 2, enqueue 4,5
4[4, 5, 6]{1,2,3,4,5,6}Dequeue 3, enqueue 6
5[5, 6]-Dequeue 4 (no neighbors)
6[6]-Dequeue 5 (no neighbors)
7[]-Dequeue 6 (no neighbors)

BFS Order: $$\boxed{1 \to 2 \to 3 \to 4 \to 5 \to 6}$$


Depth First Search (DFS)

Idea: Use a Stack (LIFO) or recursion; go deep before backtracking.

StepActionVisited
1Visit 1{1}
2Visit 2 (first neighbor of 1){1,2}
3Visit 4 (first neighbor of 2){1,2,4}
4Backtrack to 2 (4 dead-end){1,2,4}
5Visit 5{1,2,4,5}
6Backtrack to 1{1,2,4,5}
7Visit 3{1,2,4,5,3}
8Visit 6{1,2,4,5,3,6}

DFS Order: $$\boxed{1 \to 2 \to 4 \to 5 \to 3 \to 6}$$


Comparison

FeatureBFSDFS
Data structureQueue (FIFO)Stack / Recursion
Traversal mannerLevel by levelDeepest branch first
Order (this graph)$1,2,3,4,5,6$$1,2,4,5,3,6$
Typical useShortest path (unweighted)Topological sort, cycle detection

Note to examiner/student: The traversal orders above are valid only for the assumed example graph. If the real exam figure differs, apply the same procedure (queue for BFS, stack/recursion for DFS) to that graph's adjacency list to obtain the correct order.

Open this answer on its own page →

Spanning tree definition

2080 · 5 marks

Define spanning tree. Explain minimum spanning tree with example. [5]

Show solved answer

Spanning Tree and Minimum Spanning Tree

Spanning Tree

A spanning tree of a connected, undirected graph G = (V, E) is a subgraph that:

  • Includes all vertices of the graph
  • Is a tree (connected and acyclic)
  • Has exactly |V| - 1 edges

A graph with n vertices will have a spanning tree with exactly n - 1 edges.


Minimum Spanning Tree (MST)

A Minimum Spanning Tree is a spanning tree of a weighted, connected, undirected graph in which the total sum of edge weights is minimum among all possible spanning trees.

Key Properties:

  • Contains all V vertices and exactly V - 1 edges
  • No cycles are present
  • The total edge weight is minimized

Example

Consider the following weighted graph with 4 vertices:

        2
   A -------- B
   |  \       |
  6|    \ 3   | 4
   |      \   |
   D -------- C
        5

Edges and weights:

EdgeWeight
A-B2
A-C3
B-C4
A-D6
D-C5

Finding MST (using Kruskal's approach - pick minimum weight edges without forming cycle):

StepEdge SelectedWeightCycle?
1A - B2No
2A - C3No
3B - C4Yes (skip)
4D - C5No

MST Edges: A-B, A-C, D-C

        2
   A -------- B
    \        
   3 \       
      \      
       C -------- D
            5

Total MST Weight = 2 + 3 + 5 = 10

This is the minimum possible weight to connect all 4 vertices, using exactly 4 - 1 = 3 edges.


Common Algorithms to find MST:

  • Kruskal's Algorithm - sorts edges by weight and adds them greedily
  • Prim's Algorithm - grows the MST one vertex at a time from a starting vertex
Open this answer on its own page →

Graph representation using adjacency matrix

2079 · 5 marks

Explain adjacency matrix representation of graphs with example. [5]

An adjacency matrix is a 2D square matrix used to represent a graph. For a graph with n vertices, the adjacency matrix is an n × n matrix (usually denoted A), where each entry A[i][j] indicates whether there is an edge between vertex i and vertex j. --- Condition Entry Value ------ Edge exists be...

Open this answer on its own page →

Dijkstra's algorithm for shortest path

2078 · 10 marks

What is shortest path algorithm? Use Dijkstra's algorithm to find shortest path between the vertices of a and z in the graph given below.[10]

Problem asks for: definition of shortest path algorithm + Dijkstra applied to find shortest path from vertex $a$ to vertex $z$. Critical issue: The actual graph image is NOT provided in the question. Edge weights and connectivity cannot be read. Since the true graph in the exam paper is unknown, ...

Open this answer on its own page →

Graph traversal definition

2078 · 5 marks

What is graph traversal? Explain breadth first search. [5]

Graph traversal refers to the process of visiting each vertex (node) in a graph exactly once in a systematic manner. Unlike trees, graphs may contain cycles, so we need to keep track of visited vertices to avoid processing the same vertex more than once. There are two standard graph traversal tec...

Open this answer on its own page →

Prim's algorithm for MST

0 · 5 marks

Trace Prim's Algorithm to find minimum spanning tree for the following graph. [5]

Given data: - Task: Trace Prim's Algorithm to find the Minimum Spanning Tree. - Graph structure: NOT PROVIDED. The question references "the following graph," but no graph image, adjacency matrix, or edge/weight list was included in the input. Missing data: The entire graph (vertices, edges, and e...

Open this answer on its own page →