LazyShpee

nqueens

Oct 5th, 2018
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.60 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4.  
  5. int _doit(int n, int c, int *h)
  6. {
  7.     int count;
  8.     int i;
  9.     int j;
  10.  
  11.     count = (i = -1);
  12.     while ((c - n) && (j = !(++i < n) -1)) {
  13.         while (++j < c && !(h[j] == i || abs(h[j] - i) == c - j));
  14.         if (j < c) continue;
  15.         h[c] = i;
  16.         count += _doit(n, c + 1, h);
  17.     }
  18.     return (++count + !(c - n));
  19. }
  20.  
  21. int count_valid_queen_placement(int n) {
  22.     int h[n];
  23.  
  24.     return _doit(n, 0, h);
  25. }
  26.  
  27. int main(int n, char **argv)
  28. {
  29.     if (n <= 1 || (n = atoi(argv[1])) <= 0) n = 8;
  30.     printf("%d\n", count_valid_queen_placement(n));
  31. }
Advertisement
Add Comment
Please, Sign In to add comment