Skip to content
Official PYQ · 2003

GATE CS 2003 Q70 — Graph Traversals (BFS, DFS)

Explain with AI

Let G=(V,E)G= (V,E) be a directed graph with nn vertices. A path from viv_i to vjv_j in GG is a sequence of vertices (vi,vi+1,…,vjv_{i},v_{i+1}, \dots , v_j) such that (vk,vk+1)∈E(v_k, v_{k+1}) \in E for all kk in ii through j−1j-1. A simple path is a path in which no vertex appears more than once.

Let AA be an n×nn \times n array initialized as follows:

A[j,k]={1, if (j,k)∈E0, otherwiseA[j,k] = \begin{cases} 1 \text{, if } (j,k) \in E \\ 0 \text{, otherwise} \end{cases}

Consider the following algorithm:

for i=1 to n
    for j=1 to n
        for k=1 to n
            A[j,k] = max(A[j,k], A[j,i] + A[i,k]);  

Which of the following statements is necessarily true for all jj and kk after termination of the above algorithm?

Choose one option
View worked solution

Answer: D

The given algorithm is a variation of the Floyd-Warshall algorithm, where the min operation is replaced by max. Since all initial edge weights are 11, any update of the form A[j,k]=max⁡(A[j,k],A[j,i]+A[i,k])A[j,k] = \max(A[j,k], A[j,i] + A[i,k]) computes the length of some walk from jj to kk.

Let P=(v0,v1,…,vm)P = (v_0, v_1, \dots, v_m) be any simple path from j=v0j = v_0 to k=vmk = v_m of length mm. Since PP is a simple path, all its vertices are distinct. We can show by induction on the maximum index of the intermediate vertices that the algorithm will eventually find a walk of length at least mm:

  • Let ii be the vertex in the intermediate set of PP with the largest index.
  • The subpaths from jj to ii and from ii to kk only use intermediate vertices with indices strictly smaller than ii.
  • By induction, before the outer loop reaches step ii, we have A[j,i]≥length(j→i)A[j,i] \ge \text{length}(j \to i) and A[i,k]≥length(i→k)A[i,k] \ge \text{length}(i \to k).
  • At step ii, the algorithm updates A[j,k]=max⁡(A[j,k],A[j,i]+A[i,k])A[j,k] = \max(A[j,k], A[j,i] + A[i,k]), ensuring A[j,k]≥length(P)=mA[j,k] \ge \text{length}(P) = m.

Since A[j,k]A[j,k] only increases in subsequent steps, the final value of A[j,k]A[j,k] is at least the length of any simple path from jj to kk. Thus, every simple path from jj to kk contains at most A[j,k]A[j,k] edges.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Graph Traversals (BFS, DFS) questions