fast robot

 avatar
mike
plain_text
7 months ago
2.6 kB
6
Indexable
Never
#include <iostream>

using namespace std;

const int MAXN = 201;

char a[MAXN][MAXN];
int m, n, x, y, s, t, top, bot, Qx[MAXN * MAXN], Qy[MAXN * MAXN], Qz[MAXN * MAXN], d[MAXN][MAXN][4];
int h[5] = {0, 0, -1, 1};
int c[5] = {-1, 1, 0, 0};

bool ok(int i, int j){
    return (1 <= i && i <= m && 1 <= j && j <= n && a[i][j] == '0');
}

void addQueue(int x, int y, int z){
    if(top == -1) top = 0;
    bot++;
    Qx[bot] = x;
    Qy[bot] = y;
    Qz[bot] = z;
}

int getQueue1(){
    int val = Qx[top];
    return val;
}

int getQueue2(){
    int val = Qy[top];
    return val;
}

int getQueue3(){
    int val = Qz[top];
    top++;
    return val;
}

bool isEmpty(){
    return top == -1 || top > bot;
}

void BFS(int x, int y){
    top = bot = -1;
    for(int i = 1; i <= m; ++i){
        for(int j = 1; j <= n; ++j){
            for(int k = 0; k < 4; ++k)
                d[i][j][k] = 1000000;
        }
    }
    addQueue(x, y, -1);
    while(!isEmpty()){
        int u = getQueue1();
        int v = getQueue2();
        int w = getQueue3();
        for(int k = 0; k < 4; ++k){
            int new_u = u + h[k];
            int new_v = v + c[k];
            // cout << new_u << ' ' << new_v << ' ' << k << '\n';
            if(ok(new_u, new_v)){
                 // cout << new_u << ' ' << new_v << ' ' << k << endl;
                if(w == -1){
                    d[new_u][new_v][k] = 0;
                    addQueue(new_u, new_v, k);
                    continue;
                }
                if(k == w){
                    if(d[new_u][new_v][k] > d[u][v][w]){ d[new_u][new_v][k] = d[u][v][w];
                    addQueue(new_u, new_v, k);}
                }
                else{
                    if(d[new_u][new_v][k] > d[u][v][w] + 1) {d[new_u][new_v][k] = d[u][v][w] + 1;
                    addQueue(new_u, new_v, k);}
                }
            } 
        }
    }
}

void solve(){
    cin >> n >> m;
    cin >> y >> x >> t >> s;
    for(int i = 1; i <= m; ++i){
        for(int j = 1; j <= n; j++){
            cin >> a[i][j];
        }
    }
    BFS(x, y);
    int res = 1000000;
    for(int i = 0; i < 4; ++i) if(res > d[s][t][i]) res = d[s][t][i];
    if(res == 1000000) cout << -1 << endl;
    else cout << res << endl;
}

int main(){
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);
    int test; cin >> test;
    for(int t = 1; t <= test; ++t){
        // cout << "Case #" << t << endl;
        solve();
    }
    return 0;
}
Leave a Comment