Design and Analysis of Algorithms
106502Module 3: Graph and Tree Algorithms
Q1a. An adjacency matrix representation of a graph cannot contain information of (i) nodes (ii) edges (iii) direction of edges (iv) parallel edges20222m
Module 3: Graph and Tree Algorithms
View this question on its own page →An adjacency matrix representation of a graph cannot contain information of
(i) nodes
(ii) edges
(iii) direction of edges
(iv) parallel edgesWorked SolutionAnswer: (iv) parallel edges
Adjacency matrix A[i][j]=1 if edge exists. It shows node count (dimension), edges, direction (asymmetry for digraph). Simple 0/1 matrix cannot represent multiple edges between same pair (multigraph) without counts.
Q1c. The minimum number of colors needed to color a graph having n > 3 vertices and 2 edges is (i) 2 (ii) 3 (iii) 4 (iv) 120222m
Module 3: Graph and Tree Algorithms
View this question on its own page →The minimum number of colors needed to color a graph having vertices and 2 edges is
(i) 2
(ii) 3
(iii) 4
(iv) 1Worked SolutionAnswer: (i) 2
Graph with >3 vertices but only 2 edges is disconnected forest; at most needs 2 colors (bipartite, no odd cycle). Unless edge is loop, 2 colors suffice.
Q1c. Which of the following algorithms is used to find the minimum spanning tree in a weighted undirected graph? (i) Dijkstra's algorithm (ii) Kruskal's algorithm (iii) Bellman-Ford algorithm (iv) Floyd-Warshall algorithm20232m
Module 3: Graph and Tree Algorithms
View this question on its own page →Which of the following algorithms is used to find the minimum spanning tree in a weighted undirected graph?
(i) Dijkstra's algorithm
(ii) Kruskal's algorithm
(iii) Bellman-Ford algorithm
(iv) Floyd-Warshall algorithmWorked SolutionAnswer: (ii) Kruskal's algorithm (also Prim's)
Kruskal (edge greedy) and Prim (vertex greedy) both find MST. Dijkstra is shortest path, Bellman-Ford handles negatives, Floyd all-pairs.
Q1d. BFS on a graph G = (V, E) has running time (i) O(|V| + |E|) (ii) O(|V|) (iii) O(|E|) (iv) None of these20222m
Module 3: Graph and Tree Algorithms
View this question on its own page →BFS on a graph has running time
(i)
(ii)
(iii)
(iv) None of theseWorked SolutionAnswer: (i) O(|V|+|E|)
BFS visits each vertex and edge once using adjacency list.
Q1e. In an unweighted graph, which algorithm is guaranteed to find the shortest path between two nodes? (i) Depth First Search (ii) Kruskal's Algorithm (iii) Breadth First Search (iv) Prim's Algorithm20252m
Module 3: Graph and Tree Algorithms
View this question on its own page →In an unweighted graph, which algorithm is guaranteed to find the shortest path between two nodes?
(i) Depth First Search
(ii) Kruskal's Algorithm
(iii) Breadth First Search
(iv) Prim's AlgorithmWorked SolutionAnswer: (iii) Breadth First Search
BFS gives shortest path in unweighted graph (by levels). DFS not guaranteed, MST algorithms not for shortest path.
Q1e. In DFS traversal of a graph, which data structure is used to keep track of visited nodes? (i) Queue (ii) Stack (iii) Priority Queue (iv) Heap20242m
Module 3: Graph and Tree Algorithms
View this question on its own page →In DFS traversal of a graph, which data structure is used to keep track of visited nodes?
(i) Queue
(ii) Stack
(iii) Priority Queue
(iv) HeapWorked SolutionAnswer: (ii) Stack
DFS uses stack (explicit or recursion). BFS uses queue.
Q1f. Which of the following algorithms is commonly used to find the Minimum Spanning Tree of a graph? (i) Dijkstra's Algorithm (ii) Kruskal's Algorithm (iii) Bellman-Ford Algorithm (iv) Floyd-Warshall Algorithm20252m
Module 3: Graph and Tree Algorithms
View this question on its own page →Which of the following algorithms is commonly used to find the Minimum Spanning Tree of a graph?
(i) Dijkstra's Algorithm
(ii) Kruskal's Algorithm
(iii) Bellman-Ford Algorithm
(iv) Floyd-Warshall AlgorithmWorked SolutionAnswer: (ii) Kruskal's Algorithm
Explanation:
- Minimum Spanning Tree (MST) of a connected, undirected, weighted graph is found by greedy MST algorithms:
- Prim's: grows tree from a vertex, repeatedly adds minimum-weight edge crossing cut. .
- Kruskal's: sorts all edges, adds edges in increasing order skipping those forming a cycle (using Union-Find). .
- Dijkstra's, Bellman-Ford, Floyd-Warshall solve shortest paths, not MST.
- Both Prim's and Kruskal's are valid; here the option listed is Kruskal's.
Correct choice: (ii) Kruskal's Algorithm (Prim's would also be correct if listed).
- Minimum Spanning Tree (MST) of a connected, undirected, weighted graph is found by greedy MST algorithms:
Q1f. Which algorithm is used to find a Minimum Spanning Tree? (i) Dijkstra's algorithm (ii) Prim's algorithm (iii) Bellman-Ford algorithm (iv) Floyd-Warshall algorithm20242m
Module 3: Graph and Tree Algorithms
View this question on its own page →Which algorithm is used to find a Minimum Spanning Tree?
(i) Dijkstra's algorithm
(ii) Prim's algorithm
(iii) Bellman-Ford algorithm
(iv) Floyd-Warshall algorithmWorked SolutionAnswer: (ii) Prim's algorithm
Explanation:
- MST algorithms: Prim's ( with heap, with Fibonacci heap) and Kruskal's () both find Minimum Spanning Tree.
- Dijkstra's, Bellman-Ford, Floyd-Warshall are shortest-path algorithms, not MST.
- Among given options, (ii) Prim's is the only MST algorithm.
Note: Q81 lists Kruskal's as option (ii) — both Prim's and Kruskal's are correct MST algorithms; the exam chooses whichever appears in options.
Correct choice: (ii)
Q1g. If all edge weights in a graph are positive, what is the minimum number of edges in a spanning tree for a graph with vertices? (i) V (ii) V-1 (iii) V+1 (iv) 2V20252m
Module 3: Graph and Tree Algorithms
View this question on its own page →If all edge weights in a graph are positive, what is the minimum number of edges in a spanning tree for a graph with vertices?
(i) V
(ii) V-1
(iii) V+1
(iv) 2VWorked SolutionAnswer: (ii)
Explanation:
- A spanning tree of a connected graph with vertices is a tree that includes all vertices.
- Any tree with vertices has exactly edges (proof by induction; also characterizes trees among connected graphs).
- Edge weights (positive or otherwise) do not affect the count — any spanning tree, regardless of weight, has edges. Minimum spanning tree also has edges; weight affects which edges, not how many.
- Additional edges would create a cycle → not a tree.
Correct choice: (ii) (if graph disconnected, spanning forest has edges for components).
Q1g. Which of the following algorithm solves the All Pair Shortest Path problem (i) Dijkstra's (ii) Floyd's Warshall's (iii) Prim's (iv) Kruskal's20222m
Module 3: Graph and Tree Algorithms
View this question on its own page →Which of the following algorithm solves the All Pair Shortest Path problem
(i) Dijkstra's
(ii) Floyd's Warshall's
(iii) Prim's
(iv) Kruskal'sWorked SolutionAnswer: (ii) Floyd-Warshall's Algorithm
Explanation:
- All-Pairs Shortest Path (APSP) = shortest distances between every pair .
- Floyd-Warshall: DP, , handles negative edges (no negative cycles), simple triple loop:
dist[k][i][j]=min(dist[k-1][i][j], dist[k-1][i][k]+dist[k-1][k][j]). - Dijkstra's = Single-Source Shortest Path for non-negative weights; to get APSP you must run it times → , but not the canonical APSP algorithm.
- Prim's / Kruskal's = MST algorithms, unrelated to shortest paths.
Correct choice: (ii) Floyd's Warshall's (also Johnson's algorithm is another APSP method).
- Install PocketlyBudget App•POCKETLY
Pocketly on Android
Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.
Q1g. Topological sorting is only possible in: (i) Undirected Graphs (ii) Trees (iii) Directed Acyclic Graphs (iv) Weighted Graphs20242m
Module 3: Graph and Tree Algorithms
View this question on its own page →Topological sorting is only possible in:
(i) Undirected Graphs
(ii) Trees
(iii) Directed Acyclic Graphs
(iv) Weighted GraphsWorked SolutionAnswer: (iii) Directed Acyclic Graphs (DAGs)
Explanation:
- Topological sorting is a linear ordering of vertices such that for every directed edge , appears before .
- Such ordering exists iff the graph has no directed cycle. If a cycle exists, no linear extension can satisfy all precedence constraints.
- Undirected graphs have no direction → concept not defined (except trivial cases). Trees (when oriented as DAG) can be topologically sorted, but not all trees as undirected structures.
- Weighted vs. unweighted is irrelevant; only acyclicity matters.
Algorithm: DFS post-order reversed or Kahn's BFS with indegree queue, both .
Correct choice: (iii)
Q1h. Which algorithm is typically used in maximum flow problems? (i) Kruskal's Algorithm (ii) Floyd-Warshall (iii) Ford-Fulkerson (iv) Prim's Algorithm20242m
Module 3: Graph and Tree Algorithms
View this question on its own page →Which algorithm is typically used in maximum flow problems?
(i) Kruskal's Algorithm
(ii) Floyd-Warshall
(iii) Ford-Fulkerson
(iv) Prim's AlgorithmWorked SolutionAnswer: (iii) Ford-Fulkerson
Explanation:
- Maximum Flow problem: given network with capacities , find flow maximizing value from to respecting capacity and conservation.
- Ford-Fulkerson method (and Edmonds-Karp implementation, Dinic, Push-relabel) repeatedly finds augmenting paths in residual graph and augments until none remain; correctness via max-flow min-cut theorem.
- Kruskal/Prim = MST, Floyd-Warshall = APSP, not flow.
Correct choice: (iii) Ford-Fulkerson (also Edmonds-Karp, Dinic are refinements).
Q1i. What is the time complexity of topological sorting of a directed acyclic graph (DAG) with V vertices and E edges using Depth-First Search (DFS)? (i) O(V^2) (ii) O(E^2) (iii) O(V+E) (iv) O(V.E)20232m
Module 3: Graph and Tree Algorithms
View this question on its own page →What is the time complexity of topological sorting of a directed acyclic graph (DAG) with vertices and edges using Depth-First Search (DFS)?
(i)
(ii)
(iii)
(iv)Worked SolutionAnswer: (iii)
Explanation:
- Topological sort via DFS: run DFS on DAG, push vertex onto stack when finished (post-order), then reverse. Each vertex visited once, each edge examined once.
- Time = for initialization + for DFS = .
- Kahn's algorithm (BFS with indegree) is also .
- / would be for adjacency matrix without adjacency lists; with adjacency list it's linear.
Correct choice: (iii)
Q3a. Give step by step procedure to find minimal spanning tree for the given graph. 20227m
Module 3: Graph and Tree Algorithms
View this question on its own page →Give step by step procedure to find minimal spanning tree for the given graph.
Q3b. What is a Minimum Cost Spanning tree? Explain Kruskal's Minimum cost spanning tree algorithm with a suitable example.20257m
Module 3: Graph and Tree Algorithms
View this question on its own page →What is a Minimum Cost Spanning tree? Explain Kruskal's Minimum cost spanning tree algorithm with a suitable example.
Worked SolutionMinimum Cost Spanning Tree & Kruskal's Algorithm
Definition
For connected undirected weighted graph , a spanning tree is acyclic connected subgraph spanning all with edges. Minimum Cost Spanning Tree (MST) / Minimum Spanning Tree is spanning tree minimizing . If distinct weights, MST unique; otherwise multiple. Cut property and cycle property characterize MST.
Kruskal's Algorithm (Greedy)
Kruskal(G): T=∅ sort E by weight ascending make Union-Find structure for V for (u,v) in sorted E: if Find(u) != Find(v): T.add((u,v)) Union(u,v) if |T|==|V|-1: break return TCorrectness via cut property: smallest edge crossing any cut belongs to some MST; cycle property prevents adding cycle edge.
Complexities: Sorting , Union-Find → total ( inverse Ackermann). Space .
Example
Graph: , edges: AB1, AC3, BC3, BD4, CD2
- Sorted: AB1, CD2, AC3, BC3, BD4
- Add AB1 (A|B), add CD2 (C|D), add AC3 (merges {A,B} with {C,D} → {A,B,C,D}), skip BC3 (would cycle A-B-C), skip BD4. MST weight 1+2+3=6 edges AB,CD,AC.
Kruskal vs Prim
- Kruskal edge-based, good for sparse graphs; Prim vertex-based, good for dense ( with heap, naive).
- Both optimal, choice depends on density and structure.
Q4a. Solve the single source shortest path problem for the following graph considering '1' as the source vertex using Dijkstra's algorithm. 20227m
Module 3: Graph and Tree Algorithms
View this question on its own page →Solve the single source shortest path problem for the following graph considering '1' as the source vertex using Dijkstra's algorithm.
Q5a. Answer the following: (i) Compare and contrast the BFS and DFS traversal techniques in terms of their algorithmic approach, time complexity, data structures used, and typical applications. (ii) Give examples where one is preferred over the other.20247m
Module 3: Graph and Tree Algorithms
View this question on its own page →Answer the following:
(i) Compare and contrast the BFS and DFS traversal techniques in terms of their algorithmic approach, time complexity, data structures used, and typical applications.
(ii) Give examples where one is preferred over the other.Worked SolutionBFS vs DFS — Algorithmic Comparison
Aspect BFS (Breadth-First) DFS (Depth-First) Strategy Level-order using queue; explores all neighbors of current level before going deeper. Depth-first using stack (recursion); goes as deep as possible, backtracks. Algorithm queue Q={s}; visited[s]; while Q not empty: v=dequeue; for each w adj to v if not visited: visit, enqueueDFS(v): visited[v]=true; for each w adj to v if not visited: DFS(w)(or iterative stack)Time with adjacency list, with matrix. / same. Space queue + visited; worst (broad level) — more memory for wide graphs. stack/recursion, worst depth; often less memory for deep narrow graphs, but recursion may overflow. Tree vs Stack Finds shortest path (fewest edges) in unweighted graph; level = distance from source. Finds any path, not shortest; useful for connectivity, cycles, topological sort, strongly connected components. Traversal Order Visiting order by distance layers: s, all distance1, then distance2... (example linear). Visiting order by depth: s→first neighbor→its neighbor... deeper first, pre-order. Applications Shortest path unweighted, peer-to-peer, web crawling breadth, social network 1st-degree, bipartite check, Ford-Fulkerson (Edmonds-Karp uses BFS). Topological sort, cycle detection, articulation points, Kosaraju SCC, maze solving, backtracking, solving puzzles. Completeness Complete on infinite graphs with finite branching (if solution at finite depth). Not complete on infinite depth without visited set. Example on graph A→B,C etc: BFS from A order: A, B,C, D,E (level1,2) vs DFS order: A,B,D,E,C etc depending on adjacency order.
Hybrid: Iterative deepening DFS combines BFS completeness with DFS memory.
Q5a. Explain BFS algorithm in detail. Also explain its time complexity.20257m
Module 3: Graph and Tree Algorithms
View this question on its own page →Explain BFS algorithm in detail. Also explain its time complexity.
Worked SolutionBFS Algorithm — Detail & Time Complexity
Algorithm (Queue)
BFS(G, s): for each v in V: color[v]=WHITE, dist[v]=∞, parent[v]=NIL color[s]=GRAY; dist[s]=0; Q=queue(); ENQUEUE(Q,s) while Q ≠ ∅: u=DEQUEUE(Q) for each v in Adj[u]: if color[v]==WHITE: color[v]=GRAY; dist[v]=dist[u]+1; parent[v]=u; ENQUEUE(Q,v) color[u]=BLACKVariants output traversal order by recording dequeue order.
Example
Graph A→B,C etc, start A: queue [A] → visit A enqueue B,C → queue [B,C] → dequeue B enqueue D → [C,D] → dequeue C enqueue E → [D,E] → etc. Order A,B,C,D,E.
Time Complexity
- With adjacency list: Each vertex enqueued/dequeued once , each adjacency list scanned once → .
- With adjacency matrix: scan row of entries per vertex → .
Space for queue + color/dist arrays.
Properties
- Computes single-source shortest path (in edges) for unweighted graphs:
dist[v]= minimum number of edges s→v. - Produces BFS tree (parent pointers).
- Used as subroutine in Edmonds-Karp max flow, bipartite testing (2-coloring by levels), connected components.
- BFS levels correspond to distance layers; can also detect cycles / test bipartiteness by parity.
Q5b. Design a system that finds the shortest paths between various locations in a city. The locations and roads are represented using a graph. What algorithm would you use if: (i) All roads have equal length (ii) Roads have varying lengths, but no negative lengths (iii) Some roads have negative lengths Justify your choices with suitable algorithms and reasoning.20247m
Module 3: Graph and Tree Algorithms
View this question on its own page →Design a system that finds the shortest paths between various locations in a city. The locations and roads are represented using a graph. What algorithm would you use if:
(i) All roads have equal length
(ii) Roads have varying lengths, but no negative lengths
(iii) Some roads have negative lengths
Justify your choices with suitable algorithms and reasoning.Worked SolutionShortest-Path System Design — Choice by Edge Weight
City = graph vertices = locations, edges = roads, weight = length/time.
(i) All roads equal length (unweighted)
Algorithm: Breadth-First Search (BFS)
- Reason: BFS explores in increasing distance (number of edges) layers → first time target dequeued, its distance is minimum edges. with adjacency list, no need for priority queue.
- Alternative: Dijkstra with uniform weight 1 reduces to BFS (overhead wasteful).
- Use queue:
dist[s]=0, push neighbors.
(ii) Varying lengths, no negative weights (positive weighted)
Algorithm: Dijkstra's Algorithm (with binary heap , Fibonacci )
- Reason: Greedy choice of smallest tentative distance; proof relies on non-negative weights (once vertex extracted, distance final). Handles varying positive weights optimal.
- Steps:
dist[s]=0, priority queue keyed by dist; repeatedly extract min , relax edges : if update. - Why not Bellman-Ford? Correct but slower, unnecessary without negatives.
- Why not BFS? BFS assumes uniform weight → would give wrong result.
(iii) Some roads have negative lengths (negative weights, but no negative cycles reachable)
Algorithm: Bellman-Ford Algorithm () — or SPFA / Johnson's if many sources.
- Reason: Dijkstra fails with negative edges (greedy finality broken; example weight5, weight6, weight -4 → shortest to is via (2) not direct 5, Dijkstra would finalize too early).
- Bellman-Ford relaxes all edges times, then one more pass detects negative cycles.
- If negative cycle exists, shortest path undefined (); Bellman-Ford reports it.
- If graph large and only few negatives, could use Johnson's () reweighting.
Summary Table
Case Weights Algorithm Time Handles negatives? (i) uniform BFS No need (ii) varying Dijkstra (heap) No (iii) arbitrary (no neg cycle) Bellman-Ford Yes + detects cycle Justification: Choose simplest correct algorithm for constraint; progressing BFS → Dijkstra → Bellman-Ford as generality increases, trading speed for correctness.
Q5b. Explain how Bellman Ford algorithm can be used to detect the presence of negative weight cycles.20257m
Module 3: Graph and Tree Algorithms
View this question on its own page →Explain how Bellman Ford algorithm can be used to detect the presence of negative weight cycles.
Worked SolutionBellman-Ford & Negative Weight Cycle Detection
Bellman-Ford Recap
Input: directed weighted graph , source .
Init: dist[s]=0, dist[v]=∞ for v≠s repeat V-1 times: for each edge (u,v) in E: if dist[u]+w(u,v) < dist[v]: dist[v]=dist[u]+w(u,v); parent[v]=uAfter iterations, = shortest path weight from using ≤ edges (any simple path has ≤ edges). Complexity .
Detecting Negative Cycle
Extra -th iteration:
for each edge (u,v) in E: if dist[u]+w(u,v) < dist[v]: // still relaxable then v is reachable from a negative cycle (and from s) report "Negative cycle exists reachable from s"Why? In graph without negative cycles, after rounds no edge can be relaxed (shortest paths have converged). If an edge can still be relaxed, the shortest path would require ≥ edges → must repeat a vertex → contains a cycle. Since total weight decreased by going around cycle, that cycle is negative. Moreover, repeated relaxation can propagate along all vertices reachable from the cycle.
Finding cycle: To retrieve cycle, follow parent pointers from times to get into cycle, then walk until repeat.
Example
Triangle (1), (-2), (-2): sum = -4 negative. After iterations dist keeps decreasing; Vth iteration detects relaxation.
Scope
- Detects only cycles reachable from . To detect any negative cycle in graph, add super-source with 0-edge to all vertices and run Bellman-Ford.
- Dijkstra cannot detect/develop must not be used with negatives.
- Install PocketlyBudget App•POCKETLY
Pocketly on Android
Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.
Q6a. In the below given weighted graph W (Given in form of matrix), apply Bellman Ford's algorithm to find the shortest distances from source node 3. Write the time complexity of Bellman Ford's algorithm. | | 1 | 2 | 3 | 4 | 5 | |---|---|---|---|---|---| | 1 | 0 | 1 | 8 | 1 | 4 | | 2 | 1 | 0 | 12 | 4 | 9 | | 3 | 8 | 12 | 0 | 7 | 3 | | 4 | 1 | 4 | 7 | 0 | 2 | | 5 | 4 | 9 | 3 | 2 | 0 |20237m
Module 3: Graph and Tree Algorithms
View this question on its own page →In the below given weighted graph W (Given in form of matrix), apply Bellman Ford's algorithm to find the shortest distances from source node 3. Write the time complexity of Bellman Ford's algorithm.
1 2 3 4 5 1 0 1 8 1 4 2 1 0 12 4 9 3 8 12 0 7 3 4 1 4 7 0 2 5 4 9 3 2 0 Worked SolutionBellman-Ford from Source 3 on Graph with 5 Nodes (Undirected weighted)
Adjacency matrix (symmetric): edges weights:
1-2:1, 1-4:1, 1-5:4, 1-3:8, 2-4:4, 2-3:12, 2-5:9, 3-4:7, 3-5:3, 4-5:2Treat undirected as two directed edges.
Initialization
dist[3]=0, others ∞.dist = [∞,∞,0,∞,∞]indexed 1..5.Relax edges times (order 1→5 edges):
We can simulate quickly (using undirected edges both directions).
Iter1:
- From 3: to1 via8 → dist1=8, to2 via12→12, to4 via7→7, to5 via3→3
- From1 (now8): 1-2 (1): 8+1=9<12 → dist2=9; 1-4(1):8+1=9>7 no; 1-5(4):8+4=12>3 no
- From2(9): 2-4(4):9+4=13>7; 2-5(9):18>3
- From4(7): 4-5(2):7+2=9>3
- From5(3): 5-1(4):7<8 → dist1=7; 5-4(2):5<7 → dist4=5; 5-2(9):12>9? 3+9=12>9 no ; 5-3 done
After iter1: dist=[7,9,0,5,3]
Iter2:
- Check all edges: 1-2:7+1=8<9 → dist2=8; 1-4:7+1=8>5; 1-3:7+8=15>0; 2-4:8+4=12>5; 3-4:0+7=7>5; 4-5:5+2=7>3; 1-5:7+4=11>3; etc. Improvement dist2 to8.
- After iter2: [7,8,0,5,3]
Iter3:
- 2-1:8+1=9>7; 4-1:5+1=6<7 → dist1=6! ; Then 1-2 again 6+1=7<8 → dist2=7 ; Then 1-3 14>0 ; Now stable.
After iter3: dist=[6,7,0,5,3] ?? Check 4-5:5+2=7>3, 5-1:3+4=7>6, 5-4:3+2=5 equal, 2-3:7+12=19>0, 4-3:5+7=12>0. So dist=[6,7,0,5,3]
Iter4: No change → converged.
Final distances from 3:
- dist[1]=6 via 3-5(3)+5-4(2)+4-1(1)=3+2+1=6 (path 3-5-4-1)
- dist[2]=7 via 3-5-4-1-2 =3+2+1+1=7 or 3-5-4-2? 3+2+4=9 longer, so 7 is min
- dist[3]=0
- dist[4]=5 via 3-5-4 (3+2)
- dist[5]=3 direct
Check alternative 3-1 direct 8 >6, so indirect via 5-4 shorter (graph has small edges).
No negative edges → Vth iteration detects no negative cycle (no relaxation).
Time Complexity of Bellman-Ford
; with adjacency matrix → ; with list → . Space . Here , undirected (20 directed) → ~80 relaxations.
Q6a. A graph with five nodes is represented using the adjacency list as follows: | | | | | | |---|---|---|---|---| | A | -> | B (10) | C (3) | | | B | -> | C (1) | D (5) | | | C | -> | B (4) | D (8) | E (2) | | D | -> | E (7) | | | | E | -> | D (9) | | | Answer the following: (i) Draw the graph for the above adjacency list. (ii) Write the algorithm for the Breadth-First Traversal (BFS). (iii) Show the BFS traversal of the graph with the starting node as A.20247m
Module 3: Graph and Tree Algorithms
View this question on its own page →A graph with five nodes is represented using the adjacency list as follows:
A -> B (10) C (3) B -> C (1) D (5) C -> B (4) D (8) E (2) D -> E (7) E -> D (9) Answer the following:
(i) Draw the graph for the above adjacency list.
(ii) Write the algorithm for the Breadth-First Traversal (BFS).
(iii) Show the BFS traversal of the graph with the starting node as A.Worked SolutionGraph from Adjacency List + BFS
Adjacency List (directed weighted, weight in brackets)
- A → B(10), C(3)
- B → C(1), D(5)
- C → B(4), D(8), E(2)
- D → E(7)
- E → D(9)
(i) Graph Drawing (description)
Vertices A-E.
Edges: A→B (10), A→C (3), B→C (1), B→D (5), C→B (4), C→D (8), C→E (2), D→E (7), E→D (9). It's directed; no edge into A. Strongly connected component {B,C,D,E} partially.If sketched: A at top, arrows to B (right) and C (middle); B to C (down-left, 1) and D; C to B (up), to D (right), to E (down); D⟷E bidirectional with weights 7/9.
(ii) BFS Algorithm (as in Q92)
BFS(G, s): for v in V: visited[v]=false, dist[v]=∞ Q=queue(); visited[s]=true; dist[s]=0; enqueue(s) order=[] while Q not empty: u=dequeue() order.append(u) for v in Adj[u] (in list order): if not visited[v]: visited[v]=true; dist[v]=dist[u]+1; parent[v]=u; enqueue(v)Time , space . BFS ignores weights (treats as unweighted for traversal order); for weighted shortest paths use Dijkstra.
(iii) BFS Traversal Starting A (assuming adjacency order as listed)
- Init Q=[A], visited {A}, order []
- Dequeue A → order [A]; neighbors B,C not visited → enqueue B,C → Q=[B,C]
- Dequeue B → order [A,B]; neighbors C (already visited), D not visited → enqueue D → Q=[C,D]
- Dequeue C → order [A,B,C]; neighbors B already, D already, E not visited → enqueue E → Q=[D,E]
- Dequeue D → order [A,B,C,D]; neighbor E already visited (via C) → Q=[E]
- Dequeue E → order [A,B,C,D,E]; neighbor D already visited → Q=[] done.
BFS order: A → B → C → D → E
Distances (edges): dist[A]=0, dist[B]=1, dist[C]=1, dist[D]=2 (via B), dist[E]=2 (via C).Parent tree: parent[B]=A, parent[C]=A, parent[D]=B, parent[E]=C.
If adjacency order C before B, order would be A,C,B,E,D etc but standard given order yields A,B,C,D,E. BFS levels: L0 {A}, L1 {B,C}, L2 {D,E}.
Q6a. Explain the Prim's algorithm. What is the time complexity of Prim's algorithm?20257m
Module 3: Graph and Tree Algorithms
View this question on its own page →Explain the Prim's algorithm. What is the time complexity of Prim's algorithm?
Worked SolutionPrim's Algorithm & Time Complexity
Algorithm (Greedy MST)
Prim(G, s): for v in V: key[v]=∞, parent[v]=NIL, inMST[v]=false key[s]=0 Q = min-priority queue of V keyed by key while Q not empty: u = Extract-Min(Q); inMST[u]=true for each v in Adj[u]: if !inMST[v] and w(u,v) < key[v]: parent[v]=u; key[v]=w(u,v); Decrease-Key(Q,v,key[v])Growth from source , repeatedly adds minimum-weight edge crossing cut (cut property guarantees safety). Result = MST with edges, parent pointers form tree.
Example (as in Q89): start A, edges AB1 etc → picks AB1, then CD2 etc until MST weight minimal.
Correctness Sketch
Cut property: lightest edge crossing any cut belongs to some MST. Prim's cut is (inMST, rest); picking min crossing edge maintains invariant that inMST vertices are connected by MST edges.
Time Complexity
Depends on priority queue:
- Adjacency list + binary heap: = (extract-min times, decrease-key up to times).
- Adjacency list + Fibonacci heap: (amortized decrease-key ).
- Adjacency matrix + array (no heap, scan min): — best for dense graphs ().
- Adjacency matrix + binary heap: still .
Space: or for matrix.
Comparison
Prim good for dense graphs (array ), Kruskal better for sparse. Both optimal greedy MST algorithms.
Q6b. What is minimum spanning tree (MST)? Explain the steps of Prim's algorithm to find the MST using an example.20237m
Module 3: Graph and Tree Algorithms
View this question on its own page →What is minimum spanning tree (MST)? Explain the steps of Prim's algorithm to find the MST using an example.
Worked SolutionMST & Prim's Algorithm (Detailed)
MST Definition
Connected, undirected, weighted . Spanning tree with edges spanning all vertices. MST minimizes .
Prim's Algorithm (as in Q94)
Prim(G, r): key[v]=∞, parent[v]=NIL, inQueue[v]=true for all v key[r]=0; Q = min-heap on key while Q≠∅: u=Extract-Min(Q); inQueue[u]=false for v in Adj[u]: if inQueue[v] and w(u,v)<key[v]: parent[v]=u; key[v]=w(u,v); Decrease-Key(Q,v,key[v])Cut property ensures each added edge is safe.
Example Run (Graph: V=4 edges AB1 AC4 BC2 BD5 CD3)
Start A: key[A]=0
- Extract A → relax B1, C4 → key[B]=1 parent A, key[C]=4
- Extract B (min1) → relax C via2 <4 → key[C]=2 parent B; D via5 → key[D]=5
- Extract C (2) → relax D via3 <5 → key[D]=3 parent C
- Extract D (3) → done. MST edges: AB1, BC2, CD3 weight 6.
Complexity: binary heap, array, Fibonacci.
When to Use Prim vs Kruskal
- Prim vertex-growth → dense graphs ( without heap good).
- Kruskal edge-sort → sparse graphs (). Both order-wise.
Q6b. Apply the Prim's algorithm and find the optimal solution for the following graph: 20257m
Module 3: Graph and Tree Algorithms
View this question on its own page →Apply the Prim's algorithm and find the optimal solution for the following graph:

Q6b. Write the Pseudo-code for the Dijkstra's Algorithm. Further, find the single source (A) shortest path on the following graph: 20247m
Module 3: Graph and Tree Algorithms
View this question on its own page →Write the Pseudo-code for the Dijkstra's Algorithm. Further, find the single source (A) shortest path on the following graph:
Q7a. Discuss the differences between BFS and DFS in terms of traversal order, memory usage, and their applications in real-world problems.20237m
Module 3: Graph and Tree Algorithms
View this question on its own page →Discuss the differences between BFS and DFS in terms of traversal order, memory usage, and their applications in real-world problems.
Worked SolutionBFS vs DFS Differences (Traversal, Memory, Applications)
Detailed as in Q66/Q92 summary:
Traversal Order
- BFS: Level-order (queue) → visits neighbors layer by layer, yields vertices sorted by distance (edges) from source. Order: source, distance1, distance2...
- DFS: Depth-first (stack/recursion) → dives to deepest unvisited neighbor before backtracking, yields pre-order depth path.
Memory Usage
- BFS: Needs queue storing entire frontier; worst but frontier can be wide → up to for branching factor , depth ; often more memory than DFS for wide graphs.
- DFS: Stack stores current path; where = height/depth ( worst). Recursion stack but typically smaller for deep narrow graphs. Risk of recursion overflow; iterative DFS also .
- Both visited array + or graph storage.
Applications & Real-World
BFS:
- Unweighted shortest path (GPS with equal roads, social network degrees, web crawler breadth, peer-to-peer search).
- Bipartite testing, connected components, Edmonds-Karp max flow (BFS finds shortest augmenting path), broadcasting level synchrony.
DFS:
- Topological sort (DAG), cycle detection (back edge), strongly connected components (Kosaraju), articulation points/bridges, solving mazes/puzzles via backtracking, file system traversal.
- Memory-constrained search (when BFS frontier too large).
Tradeoff: Need shortest path on unweighted? BFS. Need any path / explore deep / detect cycles / topological? DFS. Need both? Use BFS for shortest, DFS for connectivity; iterative deepening combines benefits.
Q7a. What is negative weight-cycle? Write Bellman-Ford algorithm to find single source shortest distance of a directed graph.20227m
Module 3: Graph and Tree Algorithms
View this question on its own page →What is negative weight-cycle? Write Bellman-Ford algorithm to find single source shortest distance of a directed graph.
Worked SolutionNegative Weight Cycle & Bellman-Ford Algorithm
Negative Weight Cycle
Directed cycle with sum . In such graph, shortest path from source to vertices reachable from is undefined () because traversing cycle repeatedly reduces path weight arbitrarily. Example: -2, -1 → cycle -3.
Without negative cycles, shortest simple paths well-defined (≤ edges).
Bellman-Ford — Single Source Shortest Paths (SSSP) with Negatives
BellmanFord(G, s): dist[s]=0; dist[v]=∞ for v≠s; parent[v]=NIL repeat V-1 times: for each edge (u,v)∈E: if dist[u]+w(u,v) < dist[v]: dist[v]=dist[u]+w(u,v); parent[v]=u // detect negative cycle for each edge (u,v): if dist[u]+w(u,v) < dist[v]: return "Negative cycle reachable from s" (and retrieve cycle via parent) return dist, parentCorrectness: After iterations, = shortest path using ≤ edges. After , all simple paths considered. If still relaxable → ≥ edges → must contain cycle → negative.
Complexities: Time (list) / (matrix), Space . Superior to Dijkstra which fails with negatives; slower but handles them.
Finding All Negative Cycles: Add super source with 0 edges to all vertices, run once to detect any cycle in graph.
Q7a. Answer the following: (i) Explain the concept of a Minimum Spanning Tree (MST) in a connected, weighted, undirected graph. (ii) Compare and contrast Prim's and Kruskal's algorithms for finding the MST. (iii) Analyze the time complexity of both algorithms and discuss their advantages and scenarios where one is preferred over the other.20247m
Module 3: Graph and Tree Algorithms
View this question on its own page →Answer the following:
(i) Explain the concept of a Minimum Spanning Tree (MST) in a connected, weighted, undirected graph.
(ii) Compare and contrast Prim's and Kruskal's algorithms for finding the MST.
(iii) Analyze the time complexity of both algorithms and discuss their advantages and scenarios where one is preferred over the other.Worked SolutionMST Concepts, Prim vs Kruskal
(i) MST Concept
Connected, undirected, weighted . Spanning tree has edges, connects all vertices, acyclic. MST minimizes ; unique if weights distinct. Characterized by Cut Property (lightest edge crossing any cut in some MST) and Cycle Property (heaviest edge on any cycle not in MST). Applications: network design (least cable), clustering.
(ii) Compare Prim vs Kruskal
Feature Prim Kruskal Growth Vertex-based: grows tree from start vertex, adds min edge crossing cut . Edge-based: sorts all edges, adds min edge that doesn't form cycle (Union-Find). Data structure Priority queue (heap) + key[]. Union-Find (Disjoint Set) + sorting. Steps iterations extract min vertex iterations over sorted edges Complexity heap, array (dense), Fibonacci sort dominates ( as ) Graph type Good for dense ( edges) Good for sparse () Requires Connected to get single tree; else spanning forest Works on forest naturally Both greedy and optimal via cut property.
(iii) Time & Advantages / Preference
- Prim: without heap best for dense; with heap. Advantage: single tree growing → early stop or distributed. Preferred when large, graph dense, or adjacency matrix.
- Kruskal: sort. Advantage: simple, sorts edges, handles disconnected, easy parallel sort. Preferred when small (sparse) or edges already sorted.
Overall both ; choice depends on density: Prim for dense (), Kruskal for sparse ().
Q7b. Given the flow network below with capacities: | EDGE | CAPACITY | |---|---| | S -> A | 10 | | S -> C | 10 | | A -> B | 4 | | A -> C | 2 | | C -> D | 9 | | B -> T | 10 | | D -> B | 6 | | D -> T | 10 | Answer the following: (i) Use the Ford-Fulkerson algorithm to find the maximum flow from source (S) to sink (T). (ii) Show the augmenting paths selected, the bottleneck capacities on each path, and the updated residual capacities after each augmentation. (iii) Calculate the final maximum flow value.20247m
Module 3: Graph and Tree Algorithms
View this question on its own page →Given the flow network below with capacities:
EDGE CAPACITY S -> A 10 S -> C 10 A -> B 4 A -> C 2 C -> D 9 B -> T 10 D -> B 6 D -> T 10 Answer the following:
(i) Use the Ford-Fulkerson algorithm to find the maximum flow from source (S) to sink (T).
(ii) Show the augmenting paths selected, the bottleneck capacities on each path, and the updated residual capacities after each augmentation.
(iii) Calculate the final maximum flow value.Worked SolutionFord-Fulkerson Max Flow —
Network Structure
Source , sink , intermediate A,B,C,D.
Execution (Edmonds-Karp BFS for shortest augmenting path, but any path works; show one valid sequence)
Init flow 0, residual = capacities.
Augment 1: bottlenecks min(10,4,10)=4
- Push 4: residual 6, 0, 6. Flow=4
Augment 2: (via )
- Path capacities: S-A6, A-C2, C-D9, D-T10 → bottleneck 2
- Push 2: 4, 0, 7, 8. Flow=6
- Note alternative also available but we use through A to show.
Augment 3: bottleneck min(S-C10, C-D7, D-T8)=7
- Push 7: 3, 0, 1. Flow=13
Augment 4: ??? Need residual check: After 1, saturated, but reverse 4 exists. However 6 is forward.
Path 3 → is 0 residual (saturated) so no. Let's instead use remaining 4 → but 0 and 0 blocked, so cannot reach T via A. So remaining flow must go if 0 no. Actually after step3 0, so D only reachable not via C. So need alternative.Let's choose better order: Instead of exhausting C-D early, more systematic:
Re-run with better path selection (standard max flow =13? Let's compute min cut).
Min Cut analysis: Cut ? Edges crossing: 10 + 10 =20. Cut → edges 4, 9 → 13. Cut → 4, 6? Actually internal, 10, 10 → cut includes 10 + 10 =20? Wait compute: Partition vs edges 4, 9 →13. Add and are from right to T but crossing? Actually T in right, B,D in right, so not crossing? Need correct: Let's compute max flow via brute: The bottleneck is 9 + 4 =13, and 10 + 4 =14, so min is 13. So max flow =13 (limited by 4 + 9). Another cut vs edges 4 + 6 + 10 =20? Not min. So max is 13.
Our earlier flow 13 already achievable (4+2+7=13). After step3 flow=13, indeed max reached.
Check residual: 4, 3 remain but no path to T because 0, 0, 0 blocks; alternative → ??? still has 6 but unreachable (since 0). So no augmenting path → algorithm terminates.Updated Residual After Each Augmentation (summary)
Path Bottleneck Flow Residual key edges S-A-B-T 4 4 S-A6, A-B0(+4 reverse), B-T6 S-A-C-D-T 2 6 S-A4, A-C0(+2), C-D7, D-T8 S-C-D-T 7 13 S-C3, C-D0(+7), D-T1 Max Flow value =13 (4 via A-B-T, 9 via C-D-T split as 2+7). Achieved.
Any valid augmenting order yielding 13 is acceptable; another order S-C-D-B-T (6) etc also yields 13.