ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer g[3][3] = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}}
for (each i from 0 to 2)
    for (each j from 0 to 2)
        if (i == 0 AND j == 0) continue
        if (i == 0) g[i][j] = g[i][j] + g[i][j - 1]
        else if (j == 0) g[i][j] = g[i][j] + g[i - 1][j]
        else g[i][j] = g[i][j] + min(g[i - 1][j], g[i][j - 1])
    end for
end for
Print g[2][2]
  1. A. 7
  2. B. 8
  3. C. 5
  4. D. 12

Correct answer: A. 7

Each cell becomes the cheapest right/down path sum ending there. The best path is 1 → 3 → 1 → 1 → 1 (right, right, down, down), costing 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic