解題思路
逐行保留地圖中的空白,以獨立一行***切分迷宮。
從s開始廣度優先搜尋,每次擴展四鄰格,牆w與邊界不可越過,入佇列時就標記距離。
BFS按距離遞增探索,首次到e就是最短路;搜尋結束仍未到則輸出0。
每張地圖時間 O(HW),空間 O(HW)。
Step-by-step animation
教學小例:保留空白地圖的BFS
步驟 1 / 3
單列s e
起點距離0
起點距離0
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
int solve(vector<string> a) {
int h = a.size(), w = a[0].size();
queue<pair<int, int>> q;
vector<vector<int>> d(h, vector<int>(w, -1));
for (int r = 0; r < h; r++)
for (int c = 0; c < w; c++)
if (a[r][c] == 's') {
q.push({r, c});
d[r][c] = 0;
}
while (!q.empty()) {
auto [r, c] = q.front();
q.pop();
if (a[r][c] == 'e')
return d[r][c];
for (auto [dr, dc] : vector<pair<int, int>>{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) {
int y = r + dr, x = c + dc;
if (y >= 0 && y < h && x >= 0 && x < w && a[y][x] != 'w' && d[y][x] < 0) {
d[y][x] = d[r][c] + 1;
q.push({y, x});
}
}
}
return 0;
}
int main() {
string s;
vector<string> a;
while (getline(cin, s)) {
if (s == "***") {
if (!a.empty())
cout << solve(a) << '\n';
a.clear();
} else
a.push_back(s);
}
if (!a.empty())
cout << solve(a) << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。