The 8 Queens Problem

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

    Examples Solutions:

  2. 8 queens problem, reality check

    Can we apply backtracking to solve the 8 queens problem ?

  3. Formulating backtracking solution for the 8 queens problem:

  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:

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

  5. DEMO program: click here