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[4][4] = {{0,0,0,0}, {0,1,0,0}, {0,0,0,1}, {1,0,0,0}}     // 1 = blocked
Integer w[4][4] = all 0
for (each i from 0 to 3)
    for (each j from 0 to 3)
        if (g[i][j] == 1)
            w[i][j] = 0
        else if (i == 0 AND j == 0)
            w[i][j] = 1
        else
            w[i][j] = (i > 0 ? w[i - 1][j] : 0) + (j > 0 ? w[i][j - 1] : 0)
        end if
    end for
end for
Print w[3][3]
  1. A. 20
  2. B. 3
  3. C. 6
  4. D. 4

Correct answer: B. 3

w[i][j] counts right/down paths from the top-left that avoid blocked cells. Row by row: {1, 1, 1, 1}, {1, 0, 1, 2}, {1, 1, 2, 0}, {0, 1, 3, 3}, so w[3][3] = 3. With no blocked cells it would be C(6, 3) = 20.

More Pseudocode and Code Tracing questions

Exams that ask this topic