本文共 2182 字,大约阅读时间需要 7 分钟。
为了解决这个问题,我们需要找到从迷宫入口到算法书遗落位置的最短路径,同时避免经过无法进入的房间、墨菲斯托的房间和莉莉丝的房间。我们可以使用广度优先搜索(BFS)来解决这个问题,并考虑两种情况:路径中不经过任何F或M房间,或者必须经过一个F或M房间。
最后,比较这三种情况的最小值,返回最小值;如果无法找到路径,返回"IMPOSSIBLE"。
#includeusing namespace std;const int INF = 1e9;const int maxn = 1000 + 5;char g[maxn][maxn];int dx[] = {0, 1, 0, -1};int dy[] = {1, 0, -1, 0};int bfs(int x0, int y0, int x1, int y1, char forbidden) { if (x0 == x1 && y0 == y1) return 0; vector > dist(maxn, vector (maxn, INF)); dist[x0][y0] = 0; queue > q; q.push({x0, y0}); while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx < 1 || nx > maxn || ny < 1 || ny > maxn) continue; if (g[nx][ny] == forbidden) continue; if (dist[nx][ny] == INF) { dist[nx][ny] = dist[x][y] + 1; q.push({nx, ny}); if (nx == x1 && ny == y1) { return dist[nx][ny]; } } } } return dist[x1][y1];}int main() { int t; cin >> t; for (int _t = 0; _t < t; ++_t) { int n, m, r, c; cin >> n >> m >> r >> c; g = {{0}}; for (int i = 1; i <= n; ++i) { string s; cin >> s; for (int j = 1; j <= m; ++j) { g[i][j] = s[j-1]; } } int ans1 = bfs(1, 1, r, c, 'F'); int ans2 = INF; for (int x = 1; x <= n; ++x) { for (int y = 1; y <= m; ++y) { if (g[x][y] == 'F') { int d1 = bfs(1, 1, x, y, 'M'); int d2 = bfs(x, y, r, c, 'F'); if (d1 != INF && d2 != INF) { int total = d1 + d2; if (total < ans2) { ans2 = total; } } } } } int ans3 = INF; for (int x = 1; x <= n; ++x) { for (int y = 1; y <= m; ++y) { if (g[x][y] == 'M') { int d1 = bfs(1, 1, x, y, 'F'); int d2 = bfs(x, y, r, c, 'F'); if (d1 != INF && d2 != INF) { int total = d1 + d2; if (total < ans3) { ans3 = total; } } } } } int ans = min(ans1, ans2, ans3); if (ans == INF) { cout << "IMPOSSIBLE" << endl; } else { cout << ans << endl; } }}
转载地址:http://unrq.baihongyu.com/