wojiaocbj

queens

Apr 2nd, 2022
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.70 KB | None | 0 0
  1. /*
  2.  Author: Cao Beijian
  3.  Result: AC Submission_id: 4271005
  4.  Created at: Sun Apr 03 2022 12:35:17 GMT+0800 (China Standard Time)
  5.  Problem_id: 5439   Time: 3 Memory: 1676
  6. */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. int queens[25] = { 0 }, rows = 0, ans = 0;
  11. char check(int k, int p){//row k col p
  12.     int i;
  13.     for(i = 1; i < k; i++){
  14.         if((queens[i] == p) || (abs(queens[i] - p) == abs(k - i))){
  15.             return 0;
  16.         }
  17.     }
  18.     return 1;
  19. }
  20. void dfs(int k){
  21.     if(k > rows){
  22.         ans++; return;
  23.     }
  24.     else{
  25.         int i;
  26.         for(i = 1; i <= rows; i++){
  27.             if(check(k, i)){
  28.                 queens[k] = i;
  29.                 dfs(k + 1);
  30.             }
  31.             queens[k] = 0;
  32.         }
  33.     }
  34. }
  35. int main(){
  36.     scanf("%d", &rows);
  37.     dfs(1);
  38.     printf("%d\n", ans);
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment