/* * eight_queens.c -- * * Place eight queens on a chess board so that not two queens threaten * each other. A chess board has 8 x 8 squares, and a queen threatens * the chess pieces on the same row, the same column, or the same diagonal. */ #include struct position { int row; int col; }; int is_valid(struct position queens[], int row, int col); void print_chess_board(struct position queens[]); int main() { struct position queens[8]; int row, col, nchecks; row = col = nchecks = 0; while ( row < 8 ) { // Have partial solution if ( col >= 8 ) { // Cannot try any more positions on the current row // Backtrack row--; if ( row < 0 ) { // Could not find a solution; end search break; } else { // Retrieve the column stored for the current row and // try the next column col = queens[row].col + 1; } } else { // Check if current position is valid if ( is_valid(queens, row, col) ) { // Valid position; store it queens[row].row = row; queens[row].col = col; // Advance to next row row++; col = 0; } else { // Invalid position; try next column col++; } } nchecks++; } if (row == 8) { // Found solution printf("Found solution after checking %d positions\n", nchecks); print_chess_board(queens); } else { // Could not find solution printf("Could not find a solution after checkgin %d positions\n", nchecks); } return 0; } int is_valid(struct position queens[], int row, int col) { int i; if (row < 0 || row >=8 || col < 0 || col >=8) return 0; for (i=0; i