bfs求助,样例过不了
  • 板块P1141 01迷宫
  • 楼主shipeiqian
  • 当前回复2
  • 已保存回复2
  • 发布时间2022/9/5 16:38
  • 上次更新2023/10/27 12:28:37
查看原帖
bfs求助,样例过不了
632063
shipeiqian楼主2022/9/5 16:38
#include <bits/stdc++.h>
using namespace std;
const int N=10005;
int n,m,cnt=0,a[N][N],vi[N][N],ans[N*10];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
struct node{
    int x;
    int y;
}p[1000005];
bool check(node now,node nxt){
    if(nxt.x<0||nxt.y<0||nxt.x>n||nxt.y>n)return false;
    if(vi[nxt.x][nxt.y]!=0)return false;
    if(a[now.x][now.y]==a[nxt.x][nxt.y])return false;
    return true;
}
int bfs(node p){
    int ans=0;
    queue<node> q;
    q.push(p);
    vi[p.x][p.y]=cnt;
    while(!q.empty()){
        node now=q.front();
        q.pop();
        ans++;
        for(int i=0;i<4;i++){
            node nxt;
            nxt.x=now.x+dx[i];
            nxt.y=now.y+dy[i];
            if(check(now,nxt)){
                vi[nxt.x][nxt.y]=cnt;
                q.push(nxt);
            }
        }
    }
    return ans;
}
int main(){
    cin >>n >>m;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            char ch;
            cin >>ch;
            a[i][j]=(ch=='1'?1:0);
        }
    }
    while(m--){
        node p;
        cin >>p.x >>p.y;
        if(vi[p.x][p.y]!=0)cout <<ans[vi[p.x][p.y]] <<"\n";
        else{
            cnt++;
            ans[cnt]=bfs(p);
            cout <<ans[cnt] <<"\n";
        }
    }
    return 0;
}
2022/9/5 16:38
加载中...