Discuss the 8’queen’s problem.
Subject Algorithm Design
NU Year Set: 4.(a) Marks: 5 Year: 2008
 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);
            }
         }
      }
   }

 

Login to post your comment.