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:
- 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.
- 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.
- 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.
- Graph representation: Adjacency matrix space, edge check ; adjacency list space, efficient for sparse graphs.
- 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 consists of a set of vertices and a set of edges 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; has edges. |
| Weighted graph | Edges have weights/costs. |
| Subgraph | Graph formed from subset of vertices and edges. |
Useful facts: Sum of degrees in undirected graph . A regular graph of degree with vertices has edges.
1.2 Adjacency Matrix
An adjacency matrix of size stores (or weight) if edge exists, else 0/.
Pros: Edge lookup , simple, good for dense graphs, easy matrix algorithms. Cons: space even for sparse graphs, iterating neighbors takes .
1.3 Adjacency List
Each vertex stores a list of adjacent vertices (and weights for weighted graph).
Pros: space, efficient neighbor traversal, good for sparse graphs. Cons: Edge existence check , slightly more complex.
| Feature | Adjacency Matrix | Adjacency List |
|---|---|---|
| Space | ||
| Edge check | ||
| 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: 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: . 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 is a subgraph that includes all vertices, is connected, has no cycles, and contains exactly 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: 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 , if find(u)!=find(v) include edge and union sets. Stop at edges.
Complexity: or .
| 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 where if there is a path from to .
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: .
4.2 Floyd-Warshall Algorithm (All-Pairs Shortest Path)
Similar dynamic programming structure; updates shortest distance through intermediate vertex .
Works with positive/negative edges but no negative cycles. Complexity .
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 ; for each neighbor , relax: if , update.
Complexity: with min-heap. Does not work correctly with negative edge weights.
| Algorithm | Problem | Negative weights | Complexity |
|---|---|---|---|
| Warshall | Transitive closure | N/A | |
| Floyd-Warshall | All-pairs shortest path | Yes (no neg cycle) | |
| Dijkstra | Single-source shortest path | No |
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):
- Initialize: Select any start vertex (say A). Mark it visited. Set MST = {}.
- Repeat: Among all edges from visited to unvisited vertices, pick edge with minimum weight. Add edge and new vertex to MST.
- Continue until edges selected.
- 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: 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 , 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 , algorithm considers whether path from to can be improved by going through vertex . After all , matrix contains shortest path distances.
Result: All-pairs shortest path matrix obtained in 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: , where is table size (prefer prime).
Collision resolution: Chaining stores colliding keys in linked lists. Open addressing stores in table: linear probing , quadratic probing , double hashing .
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 . 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, , 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)
- (2 Marks) What is the number of edges in a regular graph of degree and vertices?
- (2 Marks) Differentiate BFS and DFS on data structure and application.
- (7 Marks) Explain adjacency matrix and adjacency list representations. For a given directed graph, compute indegree and outdegree of every vertex from adjacency matrix.
- (7 Marks) Apply Kruskal's algorithm on a weighted graph and compare its steps with Prim's algorithm.
- (7 Marks) Explain Dijkstra's algorithm with an example. Why does it fail for negative edge weights?
- (7 Marks) Write Warshall's algorithm for transitive closure and explain Floyd-Warshall all-pairs shortest path modification.