解題思路
從唯一R出發BFS,B不可進入,C與F皆可通行。
入佇列時設定距離,BFS每步成本1,所以首次到每格的距離即為最短距離;食物不能當作搜尋終點而提前停止。
收集全部已達F,若輸入列索引為r、欄為c,輸出座標為(c,M-1-r)。按(距離,x,y)排序,沒有可達食物時不印任何行。
時間 O(MN+F log F),空間 O(MN+F),F為可達食物數。
Step-by-step animation
教學小例:BFS最短路與左下角座標轉換
步驟 1 / 3
地圖RF一列
起點在左,距離0
起點在左,距離0
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
int m, n;
cin >> m >> n;
vector<string> a(m);
queue<pair<int, int>> q;
vector<vector<int>> d(m, vector<int>(n, -1));
for (int r = 0; r < m; r++) {
cin >> a[r];
for (int c = 0; c < n; c++)
if (a[r][c] == 'R') {
q.push({r, c});
d[r][c] = 0;
}
}
vector<tuple<int, int, int>> out;
while (!q.empty()) {
auto [r, c] = q.front();
q.pop();
if (a[r][c] == 'F')
out.push_back({d[r][c], c, m - 1 - r});
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 < m && x >= 0 && x < n && a[y][x] != 'B' && d[y][x] < 0) {
d[y][x] = d[r][c] + 1;
q.push({y, x});
}
}
}
sort(out.begin(), out.end());
for (auto [dist, x, y] : out)
cout << '(' << x << ',' << y << ") " << dist << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。