30pt求调

P1649 [USACO07OCT] Obstacle Course S

LonginusMonkey @ 2022-09-01 21:15:00

30pt求调

#include<bits/stdc++.h>
using namespace std;
int arr[110][110];
int beginx, beginy, endx, endy;
int is[110][110][4];
struct node{
    int x, y, z, o;
};
queue<node> que;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int main() {
    int n;
    cin >> n;
    for(int i=1; i<=n; ++i) {
        for(int j=1; j<=n; ++j) {
            char ch;
            cin >> ch;
            if(ch == ' ') {
                j--;
                continue; 
            }
            if(ch == 'A') {
                beginx = i;
                beginy = j;
                arr[beginx][beginy] = 1;
            }
            else if(ch == 'B') {
                endx = i;
                endy = j;
                arr[endx][endy] = 1;
            }
            else if(ch == '.') {
                arr[i][j] = 1; 
            }
            else
            {
                arr[i][j] = 0;
            }
        }
    }
    que.push({beginx, beginy,0,0});
    que.push({beginx, beginy,0,1});
    que.push({beginx, beginy,0,2});
    que.push({beginx, beginy,0,3});
    while(!que.empty()) {
        node t = que.front(); que.pop();
        if(t.x == endx && t.y == endy) {
            cout << t.z;
            return 0;
        }
        if(is[t.x][t.y][t.o]) {
            continue;
        }
        if(arr[t.x][t.y] == 0) {
            continue;
        }
        if(t.x > n || t.x <= 0 || t.y > n || t.y <= 0) {
            continue;
        }
        is[t.x][t.y][t.o] = 1;
        for(int i=0; i<4; ++i) {
            if(t.o == i) {
                que.push({t.x+dx[i], t.y+dy[i], t.z, t.o});
            }
            else
            {
                que.push({t.x+dx[i], t.y+dy[i], t.z+1, i});
            }
        }
    }
    cout << -1;
    return 0;
}

|