《ybtoj高效進階》第一部分第五章例題5 機器維修

SSL_wcr發表於2020-12-26

題目大意

給地圖,求從左上角到右下角需要旋轉的路是條數。

思路

bfs,注意初值和邊界
code:

#include <iostream>
#include <cstring>
#include <deque>
using namespace std;
char a[501][501];
int n, m, t, q[4][4] = { { -1, -1, -1, -1 }, { 1, 1, 0, 0 }, { -1, 1, -1, 0 }, { 1, -1, 0, -1 } };
int b[502][502];
struct f {
    int x, y, s;
} o, o2;
deque<f> p, p2;
void bfs() {
    while (p.size()) {
        o = p.front();
        p.pop_front();
        for (int i = 0; i < 4; i++) {
            int dx = o.x + q[i][0], dy = o.y + q[i][1], ds = o.s;
            if (dx < 1 || dy < 1 || dx > 1 + n || dy > 1 + m) {
                continue;
            }
            if (o.x+q[i][2]>=1&&o.y+q[i][3]>=1&&a[o.x + q[i][2]][o.y + q[i][3]] == '/' && i < 2)
                ds++;
            if (o.x+q[i][2]>=1&&o.y+q[i][3]>=1&&a[o.x + q[i][2]][o.y + q[i][3]] == 92 && i > 1)
                ds++;
            if (b[dx][dy] > ds) {
                b[dx][dy] = ds;
                o2.x = dx, o2.y = dy, o2.s = ds;
                if (ds == o.s)
                    p.push_front(o2);
                else
                    p.push_back(o2);
            }
        }
    }
    if (b[n + 1][m + 1] == 250010)
        cout << "NO SOLUTION" << endl;
    else
        cout << b[n + 1][m + 1] << endl;
    return;
}
int main() {
    cin >> t;
    while (t--) {
        p = p2;
        cin >> n >> m;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++) cin >> a[i][j], b[i][j] = 250010;
        for (int i = 1; i <= n + 1; i++) b[i][m + 1] = 250010;
        for (int i = 1; i <= m; i++) b[n + 1][i] = 250010;
        b[1][1] = 0;
        o.x = 1, o.y = 1, o.s = 0;
        p.push_front(o);
        bfs();
    }
    return 0;
}

相關文章