解題思路
先將每個障礙的兩端點正規化成左下、右上,填滿含邊界的矩形格點。鼠窩與乳酪屋也以端點範圍列舉格點。
將所有未被障礙占用的鼠窩點以距離 0 入佇列,四方向 BFS。第一次取出的乳酪屋格點,其距離是所有起點到所有終點的最小值,因為 BFS 依距離遞增走訪且每步成本相同。若佇列耗盡則無路徑。
設格點數 V=XY,障礙填格總次數 A,時間 O(V+A),空間 O(V)。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。
Step-by-step animation
教學示意(以步驟描述中的輸入為準)
步驟 1 / 3
示意空間
3×3 無障礙,鼠窩 (0,0),乳酪 (2,2)。
S..
...
..T
- 起點距離
- 0
#include <bits/stdc++.h>
using namespace std;
int main() {
int X, Y;
cin >> X >> Y;
string tag;
array<int, 4> s, t;
cin >> tag;
for (int &x : s)
cin >> x;
cin >> tag;
for (int &x : t)
cin >> x;
cin >> tag;
vector<vector<int>> d(X, vector<int>(Y, -1));
while (cin >> tag && tag != ".be") {
int x1 = stoi(tag), y1, x2, y2;
cin >> y1 >> x2 >> y2;
for (int x = min(x1, x2); x <= max(x1, x2); x++)
for (int y = min(y1, y2); y <= max(y1, y2); y++)
d[x][y] = -2;
}
queue<pair<int, int>> q;
for (int x = min(s[0], s[2]); x <= max(s[0], s[2]); x++)
for (int y = min(s[1], s[3]); y <= max(s[1], s[3]); y++)
if (d[x][y] == -1)
d[x][y] = 0, q.push({x, y});
int ans = -1;
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
if (x >= min(t[0], t[2]) && x <= max(t[0], t[2]) && y >= min(t[1], t[3]) &&
y <= max(t[1], t[3])) {
ans = d[x][y];
break;
}
for (auto [dx, dy] : vector<pair<int, int>>{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) {
int a = x + dx, b = y + dy;
if (a >= 0 && a < X && b >= 0 && b < Y && d[a][b] == -1)
d[a][b] = d[x][y] + 1, q.push({a, b});
}
}
if (ans < 0)
cout << "no path\n";
else
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。