ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer g[5][5] = {{1,1,0,0,0},
                   {1,0,0,1,1},
                   {0,0,1,0,0},
                   {1,0,1,1,0},
                   {1,0,0,0,1}}
Procedure sink(Integer i, Integer j)
    if (i < 0 OR j < 0 OR i > 4 OR j > 4 OR g[i][j] == 0)
        return
    end if
    g[i][j] = 0
    sink(i + 1, j)
    sink(i - 1, j)
    sink(i, j + 1)
    sink(i, j - 1)
End Procedure
Integer islands = 0
for (each i from 0 to 4)
    for (each j from 0 to 4)
        if (g[i][j] == 1)
            islands = islands + 1
            sink(i, j)
        end if
    end for
end for
Print islands
  1. A. 4
  2. B. 5
  3. C. 6
  4. D. 11

Correct answer: B. 5

Each new 1 starts an island, and sink wipes out everything connected to it up, down, left or right (not diagonally). The groups are: top-left {(0,0),(0,1),(1,0)}, {(1,3),(1,4)}, {(2,2),(3,2),(3,3)}, {(3,0),(4,0)} and {(4,4)}: 5 islands.

More Pseudocode and Code Tracing questions

Exams that ask this topic