提交时间:2025-10-24 15:06:15
运行 ID: 71130
#include <iostream> #include <vector> #include <queue> using namespace std; struct Point { int x, y; int steps; }; int main() { int N, M; cin >> N >> M; int N1, M1; cin >> N1 >> M1; int N2, M2; cin >> N2 >> M2; // 方向数组:上、下、左、右 int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; // BFS不使用穿越门 vector<vector<int>> dist(N + 2, vector<int>(M + 2, -1)); queue<Point> q; q.push({1, 1, 0}); dist[1][1] = 0; int min_steps = -1; while (!q.empty()) { Point p = q.front(); q.pop(); if (p.x == N && p.y == M) { min_steps = p.steps; break; } for (int i = 0; i < 4; ++i) { int nx = p.x + dx[i]; int ny = p.y + dy[i]; if (nx >= 1 && nx <= N && ny >= 1 && ny <= M && dist[nx][ny] == -1) { if (nx == N1 && ny == M1) { // 遇到第一个穿越门,从第二个穿越门开始BFS vector<vector<int>> dist2(N + 2, vector<int>(M + 2, -1)); queue<Point> q2; q2.push({N2, M2, p.steps + 1}); dist2[N2][M2] = p.steps + 1; while (!q2.empty()) { Point p2 = q2.front(); q2.pop(); if (p2.x == N && p2.y == M) { min_steps = min(min_steps == -1 ? p2.steps : min_steps, p2.steps); break; } for (int j = 0; j < 4; ++j) { int nx2 = p2.x + dx[j]; int ny2 = p2.y + dy[j]; if (nx2 >= 1 && nx2 <= N && ny2 >= 1 && ny2 <= M && dist2[nx2][ny2] == -1) { q2.push({nx2, ny2, p2.steps + 1}); dist2[nx2][ny2] = p2.steps + 1; } } } } else { q.push({nx, ny, p.steps + 1}); dist[nx][ny] = p.steps + 1; } } } } // 输出结果 cout << min_steps << endl; return 0; }