ProgrammingVery hardGoldman Sachs OA · Amazon OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer n = 6, count = 0
Integer col[n]
Function ok(Integer r, Integer c)
    for (each k from 0 to r - 1)
        if (col[k] == c OR abs(col[k] - c) == r - k)
            return false
        end if
    end for
    return true
End Function
Procedure place(Integer r)
    if (r == n)
        count = count + 1
        return
    end if
    for (each c from 0 to n - 1)
        if (ok(r, c))
            col[r] = c
            place(r + 1)
        end if
    end for
End Procedure
place(0)
Print count
  1. A. 4
  2. B. 10
  3. C. 40
  4. D. 0

Correct answer: A. 4

This backtracking counts ways to put 6 non-attacking queens on a 6 × 6 board. Surprisingly there are only 4 (fewer than the 10 for a 5 × 5 board).

More Pseudocode and Code Tracing questions

Exams that ask this topic