8 Queens on A Chessboard

Following section shows that how to place a queen in recursive manner. Please look at snippet for detailed description.

Recursive Routine 

int recurse_queen (int x, int seedx) {
  int x_int = x;

   
   // If initial queen placement is in last row, return successful
   // if initial queen placement in same row then skip it

   if (x_int == seedx){
     if (seedx == 7) return 1; // Return success
     $x_int++; // Skip this row
  }

  // Try placing queen in every location in a Row
  for (int j = 0; j < 8; j++) {
   if (place_a_queen(x_int, j)) {
      if (x_int == 7) { // Last row = Success
        return 1;
      }

      // Place Queen in next row
      if (recurse_queen (x_int+1, seedx)) {
        return 1;
      } else {
        // Unsuccessful placement – try with next location
        pick_a_queen(x_int,j);
      }
    }
  }
  return 0; // Failed
}

 

Next: Example Use

Leave a Reply

Your email address will not be published. Required fields are marked *