fork download
  1. #include <stdio.h>
  2. #include <math.h> // for abs() function
  3.  
  4. // Function to check if a queen can be placed at position x[k]
  5. int place(int x[], int k) {
  6. for (int i = 1; i < k; i++) {
  7. if ((x[i] == x[k]) || (abs(x[i] - x[k]) == abs(i - k)))
  8. return 0;
  9. }
  10. return 1;
  11. }
  12.  
  13. // Backtracking function to solve the N-Queens problem
  14. int nqueens(int n) {
  15. int x[20]; // max board size set to 20
  16. int k = 1, count = 0;
  17. x[k] = 0;
  18.  
  19. while (k != 0) {
  20. x[k]++;
  21. while ((x[k] <= n) && (!place(x, k)))
  22. x[k]++;
  23.  
  24. if (x[k] <= n) {
  25. if (k == n) {
  26. printf("\nSolution %d\n", ++count);
  27. for (int i = 1; i <= n; i++) {
  28. for (int j = 1; j <= n; j++) {
  29. printf("%c ", (j == x[i]) ? 'Q' : 'X');
  30. }
  31. printf("\n");
  32. }
  33. } else {
  34. k++;
  35. x[k] = 0;
  36. }
  37. } else {
  38. k--; // backtrack
  39. }
  40. }
  41.  
  42. return count;
  43. }
  44.  
  45. // Main function
  46. int main() {
  47. int n;
  48. printf("Enter the size of chessboard: ");
  49. scanf("%d", &n);
  50. printf("\nThe number of possibilities are %d\n", nqueens(n));
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0.01s 5320KB
stdin
4
stdout
Enter the size of chessboard: 
Solution 1
X Q X X 
X X X Q 
Q X X X 
X X Q X 

Solution 2
X X Q X 
Q X X X 
X X X Q 
X Q X X 

The number of possibilities are 2