fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <iomanip>
  4.  
  5. using namespace std;
  6.  
  7. int n, res[11][11]; // ma trận lưu lịch sử di chuyển của quân mã
  8. bool f = false; // chưa tìm thấy cách đi
  9.  
  10.  
  11. // kiểm tra tọa độ x y có nằm trong bàn cờ và chưa được thăm hay ko
  12. bool ok(int x, int y) {
  13. return (x >= 0 && y >= 0 && x < n && y < n && res[x][y] == -1);
  14. }
  15.  
  16.  
  17. // di chuyển sang x y vào bước thứ d
  18. void solve(int x, int y, int d);
  19.  
  20.  
  21. // dò các ô xung quanh điểm x y trong bước thứ d
  22. void visit(int x, int y, int d) {
  23. if (d == n * n) {
  24. f = true;
  25. return;
  26. }
  27.  
  28. const int moves[8][2] = {
  29. {1, 2}, {1, -2}, {-1, 2}, {-1, -2},
  30. {2, 1}, {2, -1}, {-2, 1}, {-2, -1}
  31. };
  32.  
  33. for (const auto& move : moves) {
  34. int nx = x + move[0];
  35. int ny = y + move[1];
  36. solve(nx, ny, d);
  37. }
  38. }
  39.  
  40. void solve(int x, int y, int d) {
  41. if (f)
  42. return;
  43. if (ok(x, y)) {
  44. res[x][y] = d + 1;
  45. visit(x, y, d + 1);
  46. if (!f)
  47. res[x][y] = -1; // Nếu tour không thành công, bỏ đánh dấu
  48. }
  49. }
  50.  
  51. int main() {
  52. cin >> n;
  53. for (int i = 0; i < n; i++)
  54. for (int j = 0; j < n; j++)
  55. res[i][j] = -1;
  56. res[0][0] = 1;
  57. visit(0, 0, 1);
  58.  
  59. if (f) {
  60. // Tính toán độ dài tối đa của số trong ma trận
  61. int max_width = to_string(n * n).length();
  62.  
  63. for (int i = 0; i < n; i++) {
  64. for (int j = 0; j < n; j++)
  65. cout << setw(max_width) << res[i][j] << " ";
  66. cout << endl;
  67. }
  68. } else {
  69. cout << "Hong thayy" << endl;
  70. }
  71.  
  72. return 0;
  73. }
  74.  
Success #stdin #stdout 0.01s 5280KB
stdin
5
stdout
 1 14 19  8 25 
 6  9  2 13 18 
15 20  7 24  3 
10  5 22 17 12 
21 16 11  4 23