You are on page 1of 3

2/2/2015

www.mathcs.emory.edu/~cheung/Courses/170.2010/Syllabus/Backtracking/8queens.html

The8QueensProblem
1. Anotherexampleofaproblemthatcanbesolvedwithbacktracking:
Place8queensona8x8chessboardsothatnoqueenattackeachother(findallsolutions)
ExamplesSolutions:

2. 8queensproblem,realitycheck
Canweapplybacktrackingtosolvethe8queensproblem?
Thesolutionsofthe8queenproblemiseasilyrecognizable
Yep
The8queensproblemcanbesolvedbymakingstepwiseimprovementtoafinalsolution
Yep,placeonequeenatatime
3. Formulatingbacktrackingsolutionforthe8queensproblem:
First,weneedtorepresentingtheplacementofqueensonachessboardusingsomethingthatthecomputer
willunderstand:

0meansnoqueenisonthesquare
1meansaqueenisplacedonthesquare
Second,noticethatweneedtoMARKthesquaresthatareattackedbysomequeen
http://www.mathcs.emory.edu/~cheung/Courses/170.2010/Syllabus/Backtracking/8queens.html

1/3

2/2/2015

www.mathcs.emory.edu/~cheung/Courses/170.2010/Syllabus/Backtracking/8queens.html

Solution:

0meanssquareisnotattackedbyanyqueen
1meanssquareisnotattackedbyonequeen
2meanssquareisnotattackedbytwoqueens
andsoon...
Noticethateachqueenmustbeplacedonadifferentrow(andcolumn)
Finally,weneedtoknowourcurrentprogressonthechessboard
4. Abacktrackingalgorithmtosolvethe8queensproblem:
GeneralstructureofaSolutionusingBacktracking
public...backtrackSolve("problemN")
{
if("problemN"isasolvedproblem)
{
print"(solved)problemN";//It'sasolution!
return;
}
for(eachpossiblestepSyoucanmakein"problemN")
{
if(stepSisalegalmove)
{
MakestepS;
backtrackSolve("problemN1");
TakestepSback;
}
}
}

Castingthe8QueensproblemintoBacktracking
publicclassQueens
{
intboard[][]={{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}};
int[][]attacked={{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
http://www.mathcs.emory.edu/~cheung/Courses/170.2010/Syllabus/Backtracking/8queens.html

2/3

2/2/2015

www.mathcs.emory.edu/~cheung/Courses/170.2010/Syllabus/Backtracking/8queens.html

{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}};
//Solve(row):nextqueenistobeplacedinrow"row"
publicvoidSolve(introw)
{
if(row==8)
{
printsolutioninboard[][];//All8queensareplaced
return;
}
for(colin0,1,2,3,4,5,6,7)
{
if(attacked[row][col]==0)
{
Placequeenonsquare(row,col);
Solve(row+1);
Removequeenfromsquare(row,col);
}
}
}
}

Placingaqueenonsquare(row,col)requiresupdating:
board[row][col]=1
Add1toallattacked[x][y]arrayelementsthatrepresentsquaresthatareattackedbyqueenplacedonsquare
(row,col)
Removingaqueenfromsquare(row,col)requiresupdating:
board[row][col]=0
Subtract1fromallattacked[x][y]arrayelementsthatrepresentsquaresthatWEREattackedbyqueenthat
WASonsquare(row,col)
5. DEMOprogram:clickhere

http://www.mathcs.emory.edu/~cheung/Courses/170.2010/Syllabus/Backtracking/8queens.html

3/3

You might also like