Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdbool.h>
- #include <stdlib.h>
- #define CHECK_ALLOC(p) if (p == NULL) {perror(""); exit(-1);}
- bool isSafe(const int colPoses[], int row, int col) {
- for (int i = 0; i < row; i++) {
- if (col == colPoses[i] || abs(row - i) == abs(colPoses[i] - col)) {
- return false;
- }
- }
- return true;
- }
- void nqueens(int *colPoses, int row, int n, int *_cnt) {
- static int cnt = 0;
- if (!row) {
- colPoses = (int*)malloc(sizeof(int) * n);
- CHECK_ALLOC(colPoses);
- }
- if (row == n) {
- cnt++;
- return;
- }
- for (int col = 0; col < n; col++) {
- if (isSafe(colPoses, row, col)) {
- colPoses[row] = col;
- nqueens(colPoses, row + 1, n, _cnt);
- colPoses[row] = -1;
- }
- }
- if (!row) {
- free(colPoses);
- *_cnt = cnt;
- cnt = 0;
- }
- }
- int main(void) {
- int n, ans = 0;
- scanf("%d", &n);
- nqueens(NULL, 0, n, &ans);
- printf("%d\n", ans);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement