求大佬帮忙看看为什么全RE

P1746 离开中山路

dreammer_mu @ 2021-03-31 14:37:29

#include <iostream>
#include <queue>
#define MAXN 1000
using namespace std;
int map[MAXN][MAXN];
int vis[MAXN][MAXN];
int sx[4]={1,-1,0,0};
int sy[4]={0,0,1,-1};
struct node{
    int x,y,step;
}t1,t2;
queue <node> q;
void bfs(int a,int b,int c,int d,int n){
    t1.x=a;t1.y=b,t1.step=0;
    q.push(t1);
    while(!q.empty()){
        t1=q.front();
        q.pop();
        if(t1.x==c && t1.y==d){
            cout<<t1.step<<endl;
            return;
        }
        for(int i=0;i<4;i++){
            t2.x=t1.x+sx[i];t2.y=t1.y+sy[i];t2.step=t1.step+1;
            vis[t2.x][t2.y]=1;
            q.push(t2);
            if( map[t2.x][t2.y] == 1 || t2.x>n ||t2.x<=0||t2.y>n ||t2.y<=0 || vis[t2.x][t2.y]==1){
                continue;
                }
        }
    }   
}
int main(){
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cin>>map[i][j];
        }
    }
    int a,b,c,d;
    cin>>a>>b>>c>>d;
    bfs(a,b,c,d,n);
    return 0;
}

脑袋要炸了,谢谢各位大佬


by metaphysis @ 2021-03-31 16:38:35

@dreammer_mu

输入时一个 n*n 字符矩阵,您把该矩阵当整数输入了,导致矩阵内的元素与实际不对应,使用二维字符数组较为合适。


by metaphysis @ 2021-03-31 16:46:32

@dreammer_mu

for(int i=0;i<4;i++){
            t2.x=t1.x+sx[i];t2.y=t1.y+sy[i];t2.step=t1.step+1;
            vis[t2.x][t2.y]=1;
            q.push(t2);
            if( map[t2.x][t2.y] == 1 || t2.x>n ||t2.x<=0||t2.y>n ||t2.y<=0 || vis[t2.x][t2.y]==1){
                continue;
                }
        }

先置入队列再判断可能会造成 vis 数组发生越界。


by dreammer_mu @ 2021-05-09 20:04:43

@metaphysis 好的好的,谢谢大佬指点!


|