Advertisement
STANAANDREY

nqueens tpa

Apr 14th, 2023 (edited)
753
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.94 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3. #include <stdlib.h>
  4. #define CHECK_ALLOC(p) if (p == NULL) {perror(""); exit(-1);}
  5.  
  6. bool isSafe(const int colPoses[], int row, int col) {
  7.   for (int i = 0; i < row; i++) {
  8.     if (col == colPoses[i] || abs(row - i) == abs(colPoses[i] - col)) {
  9.       return false;
  10.     }
  11.   }
  12.   return true;
  13. }
  14.  
  15. void nqueens(int *colPoses, int row, int n, int *_cnt) {
  16.   static int cnt = 0;
  17.   if (!row) {
  18.     colPoses = (int*)malloc(sizeof(int) * n);
  19.     CHECK_ALLOC(colPoses);
  20.   }
  21.   if (row == n) {
  22.     cnt++;
  23.     return;
  24.   }
  25.   for (int col = 0; col < n; col++) {
  26.     if (isSafe(colPoses, row, col)) {
  27.       colPoses[row] = col;
  28.       nqueens(colPoses, row + 1, n, _cnt);
  29.       colPoses[row] = -1;
  30.     }
  31.   }
  32.   if (!row) {
  33.     free(colPoses);
  34.     *_cnt = cnt;
  35.     cnt = 0;
  36.   }
  37. }
  38.  
  39. int main(void) {
  40.   int n, ans = 0;
  41.   scanf("%d", &n);
  42.   nqueens(NULL, 0, n, &ans);
  43.   printf("%d\n", ans);
  44.   return 0;
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement