Naxocist

N-Queen

Apr 10th, 2022 (edited)
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int placeCol[10], cnt;
  5.  
  6.  
  7. bool safe(int r, int c){
  8.     for(int i=1; i<=8; ++i){
  9.         if(placeCol[i] == r) return false; // same row
  10.     }
  11.  
  12.     for(int cc=1; cc<=8; ++cc){
  13.         if(placeCol[cc] == 0) continue;
  14.         if(abs(cc - c) == abs(placeCol[cc] - r)) return false; // same diagonal
  15.     }
  16.    
  17.  
  18.     return true;
  19. }
  20.  
  21.  
  22. void backtrack(int col){ // traverse through columns
  23.     if(col > 8){
  24.         for(int i=1; i<=8; ++i) printf("%d ", placeCol[i]);
  25.         printf("\n");
  26.         return ;
  27.     }
  28.    
  29.     if(placeCol[col]){
  30.         backtrack(col + 1);
  31.         return ;
  32.     }
  33.  
  34.     for(int row=1; row<=8; ++row){ // check every rows
  35.         if(safe(row, col)){
  36.             placeCol[col] = row; // choose
  37.             backtrack(col + 1); // recursive
  38.             placeCol[col] = 0; // unchoose
  39.         }
  40.     }
  41. }
  42.  
  43.  
  44. int main(){
  45.     int n; scanf("%d", &n);
  46.  
  47.     while(n--){
  48.         int r, c; scanf("%d %d", &r, &c);
  49.  
  50.         placeCol[c] = r; // fixed a queen
  51.         backtrack(1);
  52.         placeCol[c] = 0;
  53.         printf("\n");
  54.     }
  55.  
  56.     return 0;
  57. }
  58.  
Add Comment
Please, Sign In to add comment