Algorithm NQueens ( k, n) //Prints all Solution to the n-queens problem
{
for i := 1 to n do
{
if Place (k, i) then
{
x[k] := i;
The secret here is the recursion.
Let each level of indentation below indicate a level of recursion.
(not what will actually happen, as the third queen can easily be placed, but it just would've taken quite a bit more writing and/or thinking to get to a case that will actually fail)
try to place first queen
success
try to place second queen
success
try to place third queen
fail
try to place second queen in another position
success
try to place third queen
success
try to place fourth queen
Something more in line with what the code actually does: (still not what will actually happen)
first queen
i = 1
Can place? Yes. Cool, recurse.
second queen
i = 1
Can place? No.
i = 2
Can place? No.
i = 3
Can place? Yes. Cool, recurse.
third queen
i = 1
Can place? No.
i = 2
Can place? No.
... (can be placed at no position)
fail
back to second queen
i = 4
Can place? Yes. Cool, recurse.
third queen
i = 1
Can place? No.
...
I hope that helps.