提交时间:2024-08-21 17:44:39

运行 ID: 180724

#include <iostream> #include <stack> #include <queue> using namespace std; struct node { int x, y; string path; }; int main() { int x, y; cin >> x >> y; bool visited[x + 1][y + 1]; for (int i = 0; i < x + 1; i++) { for (int j = 0; j < y + 1; j++) { visited[i][j] = 0; } } queue<node> q; node n{1, 1, ""}; q.push(n); visited[n.x][n.y] = 1; while (!q.empty()) { n = q.front(); q.pop(); if (n.x == x && n.y == y) { cout << n.path << endl; return 0; } node s1{n.x + 1, n.y - 2, n.path + "1 "}, s2{n.x + 2, n.y - 1, n.path + "2 "}, s3{n.x + 2, n.y + 1, n.path + "3 "}, s4{n.x + 1, n.y + 2, n.path + "4 "}; if (1 <= s1.x && s1.x <= x && 1 <= s1.y && s1.y <= y && !visited[s1.x][s1.y]) { q.push(s1); visited[s1.x][s1.y] = 1; } if (1 <= s2.x && s2.x <= x && 1 <= s2.y && s2.y <= y && !visited[s2.x][s2.y]) { q.push(s2); visited[s2.x][s2.y] = 1; } if (1 <= s3.x && s3.x <= x && 1 <= s3.y && s3.y <= y && !visited[s3.x][s3.y]) { q.push(s3); visited[s3.x][s3.y] = 1; } if (1 <= s4.x && s4.x <= x && 1 <= s4.y && s4.y <= y && !visited[s4.x][s4.y]) { q.push(s4); visited[s4.x][s4.y] = 1; } } cout << -1 << endl; return 0; }