Created
May 10, 2015 05:28
-
-
Save 1995eaton/3e35eb0be0e274fe06e5 to your computer and use it in GitHub Desktop.
N Queens Solver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdint.h> | |
#include <time.h> | |
#define PRINT_SOLUTIONS | |
#define FANCY_PRINT | |
static inline void print_array(uint8_t *a, uint8_t n) { | |
putchar('['); | |
for (uint8_t i = 0; i < n - 1; i++) | |
printf("%d, ", a[i]); | |
if (n > 0) printf("%d", a[n - 1]); | |
puts("]"); | |
} | |
static inline void print_board(uint8_t *a, uint8_t n) { | |
for (uint8_t i = 0; i < n; i++) { | |
for (uint8_t j = 0; j < a[i]; j++) | |
printf("▄ "); | |
printf("\e[38;5;2m▄ \e[0m"); | |
for (uint8_t j = a[i] + 1; j < n; j++) | |
printf("▄ "); | |
puts(""); | |
} | |
puts("\n"); | |
} | |
static size_t solve(a, n, l, m) uint8_t *a, n, l; int m; { | |
size_t c = 0, s = 0; | |
for (uint32_t z = m, f = (1UL << n) - 1; z != f;) { | |
z |= (s = ~((-2 - z) | z)); | |
if (~m & s) { | |
uint8_t i = __builtin_ffs(s) - 1, j; | |
for (j = 0; j < l && i + j - l != a[j] && i != a[j] + j - l; j++); | |
if (j == l) a[l] = i, c += l + 1 == n ? | |
#ifdef PRINT_SOLUTIONS | |
# ifdef FANCY_PRINT | |
print_board(a, n), | |
# else | |
print_array(a, n), | |
# endif | |
#endif | |
1 : solve(a, n, l + 1, m | s); | |
} | |
} | |
return c; | |
} | |
static inline size_t n_queens(int8_t n) { | |
uint8_t a[n]; | |
return solve(&a, n, 0, 0); | |
} | |
int main(int argc, char **argv) { | |
const clock_t start = clock(); | |
printf("%sx%s: %lu solutions found\n", | |
argv[1], argv[1], n_queens(strtol(argv[1], NULL, 10))); | |
printf("finished in %lfs\n", (clock() - start) / (double) CLOCKS_PER_SEC); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment