50pts BFS求助

P1649 [USACO07OCT] Obstacle Course S

kevin1616 @ 2023-10-04 10:20:43

上代码:

#include<bits/stdc++.h>
using namespace std;
struct asdf{
    int x,y,ex;
};
int n;
int a,b,x,y;
bool d[105][105];
int step[105][105];
int vis[105][105];
int ans = 1e18;
int dx[] = { 0,-1, 0, 1};
int dy[] = {-1, 0, 1, 0};
void bfs(){
    memset(step,0x3f,sizeof(step));
    queue <asdf> q;
    q.push({a,b,0});
    step[a][b] = 0;
    while(!q.empty()){
        asdf tmp = q.front();
        q.pop();
        if(tmp.x == x && tmp.y == y){
            cout << step[tmp.x][tmp.y];
            return;
        }
        for(int i = 0;i < 4;i++){
            int nx = tmp.x + dx[i];
            int ny = tmp.y + dy[i];
            if(nx < 1 || ny < 1 || nx > n || ny > n || vis[nx][ny] >= 4 || !d[nx][ny]) continue;
            vis[nx][ny]++;
            q.push({nx,ny,i % 2 + 1});
            if(tmp.ex == 1 && i % 2 == 1) step[nx][ny] = min(step[nx][ny],step[tmp.x][tmp.y] + 1);
            else if(tmp.ex == 2 && i % 2 == 0) step[nx][ny] = min(step[nx][ny],step[tmp.x][tmp.y] + 1);
            else step[nx][ny] = min(step[nx][ny],step[tmp.x][tmp.y]);
        }
    }
    cout << -1;
}
int main(){
    cin >> n;
    for(int i = 1;i <= n;i++){
        for(int j = 1;j <= n;j++){
            char c;
            cin >> c;
            if(c == 'x') d[i][j] = 0;
            else if(c == '.') d[i][j] = 1;
            else if(c == 'A') a = i,b = j,d[i][j] = 1;
            else if(c == 'B') x = i,y = j,d[i][j] = 1;
        }
    }
    bfs();
    return 0;
}

by wuyixiang @ 2023-12-15 21:32:15

%%%


by wuyixiang @ 2023-12-15 22:08:05

更新最小值时方向可能会被覆盖,会出现问题


|