Graph Algorithms
![Question 12(c), GATE 2002: Complete a template computing all-pairs shortest-path lengths in a directed graph G. Its n×n adjacency matrix A has A[i,j]=1 for an edge i→j and 0 otherwise. Initialization loops over i=1..n and j=1..n and executes:
if A[i,j]=0 then P[i,j]=____ else P[i,j]=____;
The algorithm then has nested loops, in this exact order: for i=1..n, for j=1..n, for k=1..n, executing:
P[____,____] = min{____,____};
Complete the running-time expression O(____).](../../assets/questions/CS-2002-Q72-1.webp)
![Question 12(c), GATE 2002: Complete a template computing all-pairs shortest-path lengths in a directed graph G. Its n×n adjacency matrix A has A[i,j]=1 for an edge i→j and 0 otherwise. Initialization loops over i=1..n and j=1..n and executes:
if A[i,j]=0 then P[i,j]=____ else P[i,j]=____;
The algorithm then has nested loops, in this exact order: for i=1..n, for j=1..n, for k=1..n, executing:
P[____,____] = min{____,____};
Complete the running-time expression O(____).](../../assets/questions/CS-2002-Q72-2.webp)
Shared context
For a directed unweighted graph, binary adjacency A[i,j] equals 1 for an edge i → j and 0 otherwise. Initialize a distance table P and run the printed loops in the order i outermost, then j, then k. Standard shortest-path distances permit an empty path of length 0.
Answer & solution
Answer: O(n³), more precisely Θ(n³) (no official key was published)
1. Count initialization work. There are n choices for the first index and n for the second, so initializing P visits n² entries. Each requires only a constant-time case selection and assignment, giving Θ(n²).
2. Count the algorithm’s updates. The source has three nested loops, over i, j, and k, each running from 1 to n. There is no data-dependent early termination. Thus the innermost statement executes n×n×n = n³ times.
3. Count work per update. Reading two candidate distances, adding, comparing with the old entry, and writing the minimum take constant time under the usual RAM model with constant-time distance arithmetic. Therefore the update phase costs Θ(n³).
4. Combine the phases. Θ(n²)+Θ(n³)=Θ(n³), since the cubic term dominates as n grows. The requested big-O blank is n³, so the answer is O(n³); the tighter bound is Θ(n³).
5. Keep time and space distinct. The distance table contains n² entries and uses Θ(n²) space. Its space requirement does not reduce the cubic number of updates, and an adjacency-matrix input does not make this particular triple-loop implementation linear in the number of edges.