DuongNhi99

QuanMa

Mar 10th, 2022
470
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 5;
  5.  
  6. int xMove[8] = {2, 1, -1, -2, -2, -1, 1, 2};
  7. int yMove[8] = {1, 2, 2, 1, -1, -2, -2, -1};
  8.  
  9. int matrix[N][N];
  10.  
  11. bool isSafe(int x, int y) {
  12.     return x >= 0 && y >= 0 && x <= N - 1 && y <= N-1;
  13. }
  14.  
  15. int dfs(int x, int y, int cnt) {
  16.     for(int i=0; i < 8; i++) {
  17.         int nextX = x + xMove[i];
  18.         int nextY = y + yMove[i];
  19.        
  20.         if(cnt == N*N) return 1;
  21.        
  22.         if(isSafe(nextX, nextY)) {
  23.             if(matrix[nextX][nextY] == -1) {
  24.                 matrix[nextX][nextY] = cnt + 1;
  25.                 if(dfs(nextX, nextY, cnt+1) == 1)
  26.                     return 1;
  27.                 else
  28.                     matrix[nextX][nextY] = -1; // Solution 1.
  29.             }
  30.         }
  31.     }
  32.     matrix[x][y] = -1; // Solution 2.
  33.    
  34.     return 0;
  35. }
  36.  
  37. int main()
  38. {
  39.     int x, y; cin >> x >> y;
  40.  
  41.     for (int i = 0; i < N; i++)
  42.     for (int j = 0; j < N; j++)
  43.         matrix[i][j] = -1;
  44.    
  45.     matrix[0][0] = 1;
  46.     dfs(0, 0, 1);
  47.     for (int i = 0; i < N; i++) {
  48.     for (int j = 0; j < N; j++) {
  49.             cout << matrix[i][j] << ' ';
  50.         }
  51.         cout << "\n";
  52.     }
  53.    
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment