fork download
  1. #include <stdio.h>
  2.  
  3. #define SIZE 8
  4.  
  5. int main() {
  6. int board[SIZE][SIZE] = {0};
  7. int queensPlaced = 0;
  8.  
  9. while (queensPlaced < SIZE) {
  10. int minEliminated = 65;
  11. int bestRow = -1;
  12. int bestCol = -1;
  13.  
  14. for (int r = 0; r < SIZE; r++) {
  15. for (int c = 0; c < SIZE; c++) {
  16. if (board[r][c] == 0) {
  17. int eliminated = 0;
  18. for (int i = 0; i < SIZE; i++) {
  19. for (int j = 0; j < SIZE; j++) {
  20. if (board[i][j] == 0 && !(i == r && j == c)) {
  21. if (i == r || j == c || (i - j) == (r - c) || (i + j) == (r + c)) {
  22. eliminated++;
  23. }
  24. }
  25. }
  26. }
  27. if (eliminated < minEliminated) {
  28. minEliminated = eliminated;
  29. bestRow = r;
  30. bestCol = c;
  31. }
  32. }
  33. }
  34. }
  35.  
  36. if (bestRow != -1) {
  37. board[bestRow][bestCol] = 1;
  38. queensPlaced++;
  39. for (int i = 0; i < SIZE; i++) {
  40. for (int j = 0; j < SIZE; j++) {
  41. if (board[i][j] == 0 && (i == bestRow || j == bestCol || (i - j) == (bestRow - bestCol) || (i + j) == (bestRow + bestCol))) {
  42. board[i][j] = -1;
  43. }
  44. }
  45. }
  46. } else {
  47. break;
  48. }
  49. }
  50.  
  51. for (int r = 0; r < SIZE; r++) {
  52. for (int c = 0; c < SIZE; c++) {
  53. if (board[r][c] == 1) {
  54. printf(" Q ");
  55. } else {
  56. printf(" . ");
  57. }
  58. }
  59. printf("\n");
  60. }
  61.  
  62. return 0;
  63. }
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
 Q  .  .  .  .  .  .  . 
 .  .  .  Q  .  .  .  . 
 .  .  .  .  .  Q  .  . 
 .  .  .  .  .  .  .  Q 
 .  Q  .  .  .  .  .  . 
 .  .  .  .  Q  .  .  . 
 .  .  Q  .  .  .  .  . 
 .  .  .  .  .  .  .  .