提交时间:2024-03-09 10:16:15

运行 ID: 136538

#include <iostream> #include <vector> using namespace std; const int MAX_N = 10000; int dx[] = {1, 2, 2, 1, -1, -2, -2, -1}; int dy[] = {2, 1, -1, -2, -2, -1, 1, 2}; bool isValid(int x, int y, int n) { return x >= 1 && x <= n && y >= 1 && y <= n; } void knightTour(int n, int x, int y) { vector<vector<bool>> visited(n + 1, vector<bool>(n + 1, false)); for (int i = 0; i < 8; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; if (isValid(nx, ny, n) && !visited[nx][ny]) { cout << i + 1 << " "; visited[nx][ny] = true; x = nx; y = ny; i = -1; // Reset to try all directions according to the specified order } } cout << endl; } int main() { int x, y; cin >> x >> y; int n = max(x, y); // 保证输入的 x, y 不超过 n knightTour(n, 1, 1); return 0; }