【每日一题】29.maze (BFS 进阶)

补题链接:Here

本题代码由贺佬完成

这道题基本算一道 BFS 进阶题,有少许细节要小心 (WA1发。。

#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
using ll    = long long;
const int maxn = 300 + 10;
const int inf = 0x3f3f3f3f;

typedef pair<int, int> pii;
int n, m, q;
char g[maxn][maxn];
vector<int> f[maxn *
              maxn]; //传送阵,若为0说明没有,值代表传送阵的另一端.
int step[maxn][maxn];
int go[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
pii st, ed;
struct node {
    int x, y;
};
void bfs() {
    queue<node> q;
    node head, temp;
    head.x = st.x, head.y = st.y;
    step[st.x][st.y] = 0;
    q.push(head);
    while (!q.empty()) {
        head = q.front();
        q.pop();
        for (int i = 0; i < 4; i++) {
            temp.x = head.x + go[i][0], temp.y = head.y + go[i][1];
            if (temp.x >= 0 && temp.x < n && temp.y >= 0 && temp.y < m
                    && g[temp.x][temp.y] != '#'
                    && step[temp.x][temp.y] > step[head.x][head.y] + 1) {
                step[temp.x][temp.y] = step[head.x][head.y] + 1;
                q.push(temp);
            }
        }
        if (f[head.x * m + head.y].size() > 0) {
            for (int i = 0; i < f[head.x * m + head.y].size(); i++) {
                temp.x = f[head.x * m + head.y][i] / m,
                     temp.y = f[head.x * m + head.y][i] % m;
                if (g[temp.x][temp.y] != '#'
                        && step[temp.x][temp.y] > step[head.x][head.y] + 3) {
                    step[temp.x][temp.y] = step[head.x][head.y] + 3;
                    q.push(temp);
                }
            }
        }
    }
    if (step[ed.x][ed.y] == inf)step[ed.x][ed.y] = -1;
    cout << step[ed.x][ed.y] << endl;
}
void solve() {
    bfs();
}
int main() {
    // ios::sync_with_stdio(false)
    while (cin >> n >> m >> q) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cin >> g[i][j];
                if (g[i][j] == 'S') {
                    st.x = i, st.y = j;
                }
                else if (g[i][j] == 'T') {
                    ed.x = i, ed.y = j;
                }
                step[i][j] = inf;
            }
        }
        for (int i = 0; i <= n * m; i++) {
            f[i].clear();
        }
        pii a, b;
        int temp1, temp2;
        for (int i = 0; i < q; i++) {
            cin >> a.x >> a.y >> b.x >> b.y;
            temp1 = a.x * m + a.y, temp2 = b.x * m + b.y;
            f[temp1].push_back(temp2);
        }
        solve();
    }
    return 0;
}

The desire of his soul is the prophecy of his fate
你灵魂的欲望,是你命运的先知。

原文地址:https://www.cnblogs.com/RioTian/p/14787303.html