Top Banner Ad

BCS301 — Unit 5: Graphs

Table of Contents (24 sections)

BCS301 · DATA STRUCTURE · Unit 5

Graphs

Unit Scope & Exam Weightage: Unit 5 covers graph terminology, graph representations, traversals, connected components, spanning trees, minimum spanning trees, transitive closure, and shortest path algorithms. AKTU frequently asks for Prim/Kruskal MST, Dijkstra/Floyd-Warshall shortest paths, BFS/DFS, adjacency matrix/list representation, and core graph terminology.


Front Page: Importance-Wise Topic Roadmap (PYQ Frequency × Marks)

Priority Topic (Exact Syllabus) PYQs Asked Marks Weightage Tag
1 Minimum Cost Spanning Trees: Prims and Kruskal algorithm 1 (2023-24, 2025-26) 7m Survival Mode Predicted
2 Data Structure for Graph Representations: Adjacency Matrices, Adjacency List 3 (2023-24, 2024-25) 7m × 3 = 21m Survival Mode Predicted
3 Transitive Closure and Shortest Path algorithm: Warshal Algorithm and Dijikstra Algorithm 2 (2023-24, 2025-26) 7m × 2 = 14m Core Concept Numerical
4 Graph Traversal: Depth First Search and Breadth First Search 1 (2024-25) 7m Core Concept
5 Terminology used with Graph 2 (2023-24, 2024-25) 7m + 2m = 9m Core Concept
6 Connected Component, Spanning Trees 1 (2023-24) 2m Quick Scoring

2-Hour Last-Night Survival Checklist:

  1. MST algorithms: Practice Prim (grow tree from a vertex using min edge to visited set) and Kruskal (sort edges, add if no cycle using DSU). Write edge-selection order and total cost.
  2. Shortest paths: Dijkstra works for non-negative weights (single source); Floyd-Warshall computes all-pairs shortest paths and can detect negative cycles; Warshall computes transitive closure.
  3. BFS/DFS: BFS uses queue and gives shortest path in unweighted graph; DFS uses stack/recursion and is used for cycle detection, components, topological sort.
  4. Graph representation: Adjacency matrix O(V2)O(V^2) space, edge check O(1)O(1); adjacency list O(V+E)O(V+E) space, efficient for sparse graphs.
  5. Terminology: Revise degree, in/out degree, path, cycle, connected/strongly connected, complete graph, weighted graph, spanning tree.

1. Graph Terminology and Representations

Graph: A graph G=(V,E)G=(V,E) consists of a set of vertices VV and a set of edges EE connecting pairs of vertices. Graphs may be directed or undirected, weighted or unweighted, and may contain cycles.

1.1 Terminology Used with Graph

Term Meaning
Vertex/Node An entity in the graph.
Edge/Arc Connection between vertices. In directed graph, edge has direction.
Adjacent vertices Vertices connected by an edge.
Degree Number of edges incident on a vertex (undirected). Loop counted twice in some conventions.
In-degree/Out-degree In directed graph, incoming/outgoing edge counts.
Path Sequence of vertices connected by edges.
Cycle Path that starts and ends at same vertex with no repeated edge/vertex (simple cycle).
Connected graph Undirected graph with path between every pair of vertices.
Strongly connected Directed graph with directed path between every pair.
Complete graph Every pair of distinct vertices connected; KnK_n has n(n−1)/2n(n-1)/2 edges.
Weighted graph Edges have weights/costs.
Subgraph Graph formed from subset of vertices and edges.

Useful facts: Sum of degrees in undirected graph =2∣E∣=2|E|. A regular graph of degree dd with nn vertices has nd/2nd/2 edges.

1.2 Adjacency Matrix

An adjacency matrix AA of size V×VV\times V stores A[i][j]=1A[i][j]=1 (or weight) if edge exists, else 0/∞\infty.

Pros: Edge lookup O(1)O(1), simple, good for dense graphs, easy matrix algorithms. Cons: O(V2)O(V^2) space even for sparse graphs, iterating neighbors takes O(V)O(V).

1.3 Adjacency List

Each vertex stores a list of adjacent vertices (and weights for weighted graph).

Pros: O(V+E)O(V+E) space, efficient neighbor traversal, good for sparse graphs. Cons: Edge existence check O(deg(v))O(deg(v)), slightly more complex.

Feature Adjacency Matrix Adjacency List
Space O(V2)O(V^2) O(V+E)O(V+E)
Edge check O(1)O(1) O(deg(v))O(deg(v))
Add vertex costly resize easy
Best for Dense graph Sparse graph

After-Topic PYQ (2024-25 Sec C Q6b, 7 Marks): Explain the following graph terminologies with examples: (i) Graph (ii) Weighted Graph (iii) Degree of a Vertex After-Topic PYQ (2024-25 Sec B Q5b, 7 Marks): Explain two ways to represent a graph in memory and compare their advantages: (i) Adjacency Matrix (ii) Adjacency List After-Topic PYQ (2023-24 Sec C Q5b, 7 Marks): Write a program in C language to compute the indegree and outdegree of every vertex of a directed graph when the graph is represented by an adjacency matrix. After-Topic PYQ (2023-24 Sec A Q1j, 2 Marks): What is the number of edges in a regular graph of degree d and n vertices.


2. Graph Traversal and Connected Components

2.1 Breadth First Search (BFS)

BFS visits vertices level by level from a source using a queue.

BFS(G,s): mark s visited; enqueue s;
while queue not empty: u=dequeue; for each v adjacent to u if not visited mark, enqueue

Time: O(V+E)O(V+E) with adjacency list. Uses: shortest path in unweighted graph, level order, connected components.

2.2 Depth First Search (DFS)

DFS explores as deep as possible before backtracking using a stack or recursion.

DFS(u): mark u visited; for each v adjacent to u if not visited DFS(v)

Time: O(V+E)O(V+E). Uses: cycle detection, topological sort, connected/strongly connected components, path finding.

2.3 Connected Component

A connected component of an undirected graph is a maximal connected subgraph. Algorithm: run BFS/DFS from every unvisited vertex; each run discovers one component.

After-Topic PYQ (2024-25 Sec C Q6a, 7 Marks): Explain the Depth-first Search (DFS) algorithm with the help of an example graph. Which data structure is used for DFS and BFS? After-Topic PYQ (2023-24 Sec A Q1k, 2 Marks): Write an algorithm to obtain the connected components of a graph.


3. Spanning Trees and Minimum Cost Spanning Trees

Spanning Tree: A spanning tree of a connected undirected graph G=(V,E)G=(V,E) is a subgraph that includes all vertices, is connected, has no cycles, and contains exactly ∣V∣−1|V|-1 edges. A Minimum Cost Spanning Tree (MST) minimizes total edge weight.

3.1 Prim's Algorithm

Prim grows MST from a starting vertex by repeatedly adding the minimum-weight edge connecting a visited vertex to an unvisited vertex.

Steps: Initialize key of start = 0, others = ∞. Use min-priority queue. Extract min key vertex, include in MST, update keys of adjacent unvisited vertices.

Complexity: O(Elog⁡V)O(E\log V) with binary heap.

3.2 Kruskal's Algorithm

Kruskal sorts all edges by weight and adds an edge if it does not form a cycle (checked by Disjoint Set Union/Union-Find).

Steps: Sort edges ascending. For each edge (u,v)(u,v), if find(u)!=find(v) include edge and union sets. Stop at V−1V-1 edges.

Complexity: O(Elog⁡E)O(E\log E) or O(Elog⁡V)O(E\log V).

Feature Prim Kruskal
Strategy Grow from vertex Add smallest safe edge globally
Data structure Priority queue Sorting + DSU
Good for Dense graphs Sparse graphs
Starts with A vertex Edge list

After-Topic PYQ (2023-24 Sec B Q5a / 2025-26 Sec B Q5a, 7 Marks): Use Prim’s Algorithm to compute the Minimum Spanning Tree for the given weighted graph.


4. Transitive Closure and Shortest Path Algorithms

4.1 Warshall's Algorithm (Transitive Closure)

Warshall computes reachability matrix RR where R[i][j]=1R[i][j]=1 if there is a path from ii to jj.

R = adjacency matrix (with 1 on diagonal for closure, as per convention)
for k=0 to V-1:
  for i=0 to V-1:
    for j=0 to V-1:
      R[i][j] = R[i][j] OR (R[i][k] AND R[k][j])

Complexity: O(V3)O(V^3).

4.2 Floyd-Warshall Algorithm (All-Pairs Shortest Path)

Similar dynamic programming structure; updates shortest distance through intermediate vertex kk.

dist[i][j]=min⁡(dist[i][j],  dist[i][k]+dist[k][j])dist[i][j]=\min(dist[i][j],\;dist[i][k]+dist[k][j])

Works with positive/negative edges but no negative cycles. Complexity O(V3)O(V^3).

4.3 Dijkstra's Algorithm (Single-Source Shortest Path)

Dijkstra finds shortest paths from a source to all vertices for non-negative edge weights.

Steps: Set distance of source 0, others ∞. Use min-priority queue. Extract minimum distance vertex uu; for each neighbor vv, relax: if dist[u]+w(u,v)<dist[v]dist[u]+w(u,v)<dist[v], update.

Complexity: O((V+E)log⁡V)O((V+E)\log V) with min-heap. Does not work correctly with negative edge weights.

Algorithm Problem Negative weights Complexity
Warshall Transitive closure N/A O(V3)O(V^3)
Floyd-Warshall All-pairs shortest path Yes (no neg cycle) O(V3)O(V^3)
Dijkstra Single-source shortest path No O((V+E)log⁡V)O((V+E)\log V)

After-Topic PYQ (2025-26 Sec C Q5b, 7 Marks): Write and explain the Floyd-Warshall algorithm to find all-pair shortest paths. Apply it to the given graph. After-Topic PYQ (2023-24 Sec B Q5b, 7 Marks): Consider the following graph and using Dijkstra Algorithm find the shortest path.


Solved Exam-Ready Questions

Solved Q1 (2023-24 Sec B Q5a / 2025-26 Sec B Q5a, 7 Marks)

Q: Use Prim’s Algorithm to compute the Minimum Spanning Tree for the given weighted graph.

Answer (method to write in exam):

  1. Initialize: Select any start vertex (say A). Mark it visited. Set MST = {}.
  2. Repeat: Among all edges from visited to unvisited vertices, pick edge with minimum weight. Add edge and new vertex to MST.
  3. Continue until V−1V-1 edges selected.
  4. Report: List selected edges in order and compute total cost.

Example format: Selected edges: (A,B,2), (B,C,3), (C,D,1)... Total MST weight = sum. State that Prim avoids cycles by only adding edges to unvisited vertices.

Result: Prim's algorithm yields an MST of total minimum cost for a connected weighted undirected graph.


Solved Q2 (2024-25 Sec C Q6a, 7 Marks)

Q: Explain the Depth-first Search (DFS) algorithm with the help of an example graph. Which data structure is used for DFS and BFS?

Answer:

DFS: Start at source, mark visited, recursively visit an unvisited adjacent vertex. Backtrack when no unvisited adjacent vertex remains.

Algorithm: DFS(G,u): visited[u]=true; print(u); for each v in Adj[u] if not visited[v] DFS(G,v).

Example: For graph A-B, A-C, B-D, B-E, DFS from A may visit A,B,D,E,C (adjacency order dependent).

Data structures: DFS uses stack (explicit or recursion call stack). BFS uses queue.

Complexity: O(V+E)O(V+E) using adjacency list.


Solved Q3 (2025-26 Sec C Q5b, 7 Marks)

Q: Write and explain the Floyd-Warshall algorithm to find all-pair shortest paths. Apply it to the given graph.

Answer:

Floyd-Warshall: Initialize dist[i][j]=w(i,j), dist[i][i]=0, dist[i][j]=∞ if no edge. For each intermediate vertex kk, update all pairs:

for k in 1..V:
  for i in 1..V:
    for j in 1..V:
      if dist[i][k]+dist[k][j] < dist[i][j]:
        dist[i][j]=dist[i][k]+dist[k][j]

Explanation: At stage kk, algorithm considers whether path from ii to jj can be improved by going through vertex kk. After all kk, matrix contains shortest path distances.

Result: All-pairs shortest path matrix obtained in O(V3)O(V^3) time.


Additional Unit 5 Solved Questions (from unit PYQ set)

Solved Q4 (2025-26 Sec C Q5a, 7 Marks)

Q: What is hashing? Explain the division method to compute the hash function and the collision resolution strategies used in hashing.

Answer:

Hashing maps keys to hash table indices using hash function for fast access. Division method: h(k)=kmod  mh(k)=k \mod m, where mm is table size (prefer prime).

Collision resolution: Chaining stores colliding keys in linked lists. Open addressing stores in table: linear probing (h(k)+i)mod  m(h(k)+i)\mod m, quadratic probing (h(k)+i2)mod  m(h(k)+i^2)\mod m, double hashing (h1(k)+ih2(k))mod  m(h_1(k)+i h_2(k))\mod m.

Result: Division method is simple; chaining handles collisions flexibly, while probing keeps data in table.


Solved Q5 (2024-25 Sec B Q5a, 7 Marks)

Q: Construct a Hash table that contains 10 buckets and uses linear probing to resolve collisions. The key values are integers and the Hash function used is key%10key \% 10. Insert values 43, 165, 62, 123, 142 in the table. Show all the steps and find the location of the key value 142?

Solution:

Table size 10, h(k)=kmod  10h(k)=k\mod 10, linear probing.

Key h(k) Probe/Location Table action
43 3 3 free index 3 = 43
165 5 5 free index 5 = 165
62 2 2 free index 2 = 62
123 3 3 occupied, 4 free index 4 = 123
142 2 2 occupied, 3 occupied, 4 occupied, 5 occupied, 6 free index 6 = 142

Result: Key 142 is located at index 6.


Practice Questions (Self-Test)

  1. (2 Marks) What is the number of edges in a regular graph of degree dd and nn vertices?
  2. (2 Marks) Differentiate BFS and DFS on data structure and application.
  3. (7 Marks) Explain adjacency matrix and adjacency list representations. For a given directed graph, compute indegree and outdegree of every vertex from adjacency matrix.
  4. (7 Marks) Apply Kruskal's algorithm on a weighted graph and compare its steps with Prim's algorithm.
  5. (7 Marks) Explain Dijkstra's algorithm with an example. Why does it fail for negative edge weights?
  6. (7 Marks) Write Warshall's algorithm for transitive closure and explain Floyd-Warshall all-pairs shortest path modification.