wojiaocbj

queens

Apr 7th, 2022
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6. #include <time.h>
  7. #pragma warning(disable:4996)
  8. typedef long long LL;
  9. typedef unsigned long long ULL;
  10. #define MAX(a,b) (((a)>(b))?(a):(b))
  11. #define SETBIT(gpio,bit) ((gpio)|=(1u<<(bit)))
  12. #define RESETBIT(gpio,bit) ((gpio)&=~(1u<<(bit)))
  13. #define READBIT(gpio,bit) (((gpio)>>(bit))&1)
  14. #define CROL(X,i,n) ((((X)<<(i))|((X)>>((n)-(i))))&((1ull<<(n))-1ull))
  15. #define CROR(X,i,n) ((((X)>>(i))|((X)<<((n)-(i))))&((1ull<<(n))-1ull))
  16. int queens[25] = { 0 }, rows = 0, ans = 0;
  17. char check(int k, int p){//row k col p
  18.     int i;
  19.     for(i = 1; i < k; i++){
  20.         if((queens[i] == p) || (abs(queens[i] - p) == abs(k - i))){
  21.             return 0;
  22.         }
  23.     }
  24.     return 1;
  25. }
  26. void dfs(int k){
  27.     int i;
  28.     if(k > rows){
  29.         if(ans < 3){
  30.             for(i = 1; i < k; i++){
  31.                 printf("%d ", queens[i]);
  32.             }
  33.             putchar('\n');
  34.         }  
  35.         ans++; return;
  36.     }
  37.     else{
  38.         for(i = 1; i <= rows; i++){
  39.             if(check(k, i)){
  40.                 queens[k] = i;
  41.                 dfs(k + 1);
  42.             }
  43.             queens[k] = 0;
  44.         }
  45.     }
  46. }
  47. int main(){
  48. #ifdef _DEBUG
  49.     FILE *fp = freopen("../../../input.txt", "r", stdin);
  50.     //FILE *fp2 = freopen("output.txt", "w", stdout);
  51. #endif // _DEBUG
  52.     scanf("%d", &rows);
  53.     dfs(1);
  54.     printf("%d\n", ans);
  55. #ifdef _DEBUG
  56.     freopen("CON", "r", stdin);
  57.     //freopen("CON", "w", stdout);
  58.     system("pause");
  59. #endif // _DEBUG
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment