# 8 Queens Problem Recursively

Does anyone have an example to solve the 8 Queens problem recursively?

Place 8 queens on a chess board so that no two queens are attacking each other
Asked:
###### Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Here is an example which I just wrote for you. It will lose its indentation when posted, but I hope you can read it anyway. It sets up a chessboard, tries adding a queen at a time in a free position, and for each time marks the squares which cannot be used, and tries to add a new queen recursively.

type
pos = (Free, Queen, Busy);
chessboard = array[1..8,1..8] of pos;

Var
r,k: integer;
emptyboard : chessboard;

function min(a,b:integer):integer;
begin
if a<b then min := a else min := b;
end;

function findsolution(board : chessboard; level : Integer): Boolean;
Var
r,k:integer;
i:integer;
ch:char;
boardcopy:chessboard;
begin
findsolution:=false;
boardcopy := board;
for r:=1 to 8 do
for k:=1 to 8 do
if boardcopy[r, k] = Free Then
begin
if level+1 = 8 then begin
writeln;
writeln('Solution:');
for r:=1 to 8 do
begin
for k:=1 to 8 do
If boardcopy[r, k] = Queen then
write('Q')
else
write(' ');
writeln;
end;
findsolution:=true;
exit;
end;

board:=boardcopy;
for i:=1 to 8 do
board[i, k]:=Busy;
for i:=1 to 8 do
board[r, i]:=Busy;
for i:=1-min(r,k) to min(9-r,9-k)-1 do
board[r+i, k+i]:=Busy;
for i:=1-min(9-r,k) to min(r, 9-k)-1 do
board[r-i, k+i]:=Busy;

board[r, k]:=Queen;

if findsolution(board, level+1) Then
begin
findsolution:=True;
exit;
end;

end;

end;

begin

for r:=1 to 8 do
for k:=1 to 8 do
emptyboard[r,k]:=Free;

if findsolution(emptyboard, 0) then
writeln('A solution was found');
end.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Pascal

From novice to tech pro — start learning today.