# The 8 Queens Problem

1. Another example of a problem that can be solved with backtracking:

• Place 8 queens on a 8x8 chess board so that no queen attack each other (find all solutions)

Examples Solutions:

2. 8 queens problem, reality check

Can we apply backtracking to solve the 8 queens problem ?

• The solutions of the 8 queen problem is easily recognizable
• Yep

• The 8 queens problem can be solved by making stepwise improvement to a final solution
• Yep, place one queen at a time

3. Formulating backtracking solution for the 8 queens problem:

• First, we need to representing the placement of queens on a chess board using something that the computer will understand:

• 0 means no queen is on the square
• 1 means a queen is placed on the square

• Second, notice that we need to MARK the squares that are attacked by some queen

Solution:

• 0 means square is not attacked by any queen
• 1 means square is not attacked by one queen
• 2 means square is not attacked by two queens
• and so on...

• Notice that each queen must be placed on a different row (and column)

• Finally, we need to know our current progress on the chess board

4. A backtracking algorithm to solve the 8 queens problem:

 General structure of a Solution using Backtracking ``` public ... backtrackSolve("problem N") { if ( "problem N" is a solved problem ) { print "(solved) problem N"; // It's a solution ! return; } for ( each possible step S you can make in "problem N" ) { if ( step S is a legal move ) { Make step S; backtrackSolve("problem N-1"); Take step S back; } } } ```

 Casting the 8 Queens problem into Backtracking ``` public class Queens { int board[][] = { {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}, {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): next queen is to be placed in row "row" public void Solve(int row) { if ( row == 8 ) { print solution in board[][]; // All 8 queens are placed return; } for ( col in 0, 1, 2, 3, 4, 5, 6, 7 ) { if ( attacked[row][col] == 0 ) { Place queen on square (row,col); Solve(row+1); Remove queen from square (row,col); } } } } ```

Placing a queen on square (row,col) requires updating:

• board[row][col] = 1

• Add 1 to all attacked[x][y] array elements that represent squares that are attacked by queen placed on square (row,col)

Removing a queen from square (row,col) requires updating:

• board[row][col] = 0

• Subtract 1 from all attacked[x][y] array elements that represent squares that WERE attacked by queen that WAS on square (row,col)