fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N=10;
  5. int n, k, ans;
  6. bool check[N][N], col[N];
  7.  
  8. int di[8]={-2, -2, -1, 1, 2, 2, -1, 1};
  9. int dj[8]={-1, 1, 2, 2, -1, 1, -2, -2};
  10. bool inside(int i, int j) //hàm kiểm tra ô (i, j) có nằm trong bàn cờ hay không
  11. {
  12. return i>0 && i<=n && j>0 && j<=n;
  13. }
  14. int cnt;
  15. void btrack(int i)
  16. {
  17. if(i>n){
  18. if(cnt==k) ++ans;
  19. return;
  20. }
  21. if(cnt<k){ //trường hợp đặt tại hàng i
  22. for(int j=1;j<=n;++j){
  23. if(col[j] || check[i][j]) continue;
  24.  
  25. ++cnt;
  26. col[j]=1;
  27. for(int x=0;x<8;++x){
  28. int ni=i+di[x], nj=j+dj[x]; //vị trí từ ô (i, j) có thể di tới theo kiểu quân Mã
  29. if(inside(ni, nj)) check[ni][nj]=1;
  30. }
  31.  
  32. btrack(i+1);
  33.  
  34. --cnt;
  35. col[j]=0;
  36. for(int x=0;x<8;++x){
  37. int ni=i+di[x], nj=j+dj[x];
  38. if(inside(ni, nj)) check[ni][nj]=0;
  39. }
  40. }
  41. }
  42. btrack(i+1); //trường hợp không đặt tại hàng i
  43. }
  44.  
  45. int main()
  46. {
  47. ios::sync_with_stdio(0);
  48. cin.tie(0); cout.tie(0);
  49.  
  50. cin >> n >> k;
  51. btrack(1);
  52. cout << ans;
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
1