procedure main() local n write("type n for n x n board:") while n:=read() # as long as not eof do every write("Answer=" || show( queen(n) ) ) # solve for n*n board end procedure queen(n) # solve for the n*n board suspend place(n, n, list(n,0)) # return a solution write("finished") # when no more solutions end procedure place(row, n, board) # place the row-th queen on a column #debug write("row" || row || " :" || show(board) ) if row=0 then suspend board # if all n queens placed else every board[row] := 1 to n # else try all cols for row-th queen do if valid(row, 1, board) then suspend place(row-1, n, board) end procedure valid(row, diag, board) # check no queens threaten #debug write(" valid?" || row || " " || diag || " " || show(board) ) return( (row+diag > *board) | ((board[row] ~= board[row+diag]) & # no common column (board[row]+diag ~=board[row+diag]) & # no common up diag (board[row]-diag ~=board[row+diag]) & # no common down diag valid( row, diag+1,board) ) ) end procedure show( l ) # convert board (a list) to a string return if *l ~= 0 then " " || l[1] || show(l[2:0]) else " " end # \fBSolve the n-Queens Problem.\fP