为什么bfs过不了,dfs可以

P8662 [蓝桥杯 2018 省 AB] 全球变暖

FreeEvil767 @ 2024-01-31 19:15:43

为啥这一段过不了啊?(#3,#5-10 TE)

#include <bits/stdc++.h>
using namespace std;
int n,dx[5]={0,1,-1,0,0},dy[5]={0,0,0,1,-1};
bool vst[1009][1009],l[1009][1009];
char c[1009][1009];
struct node{
    int x,y;
};
queue<node> q;
bool vaild(int x,int y){
    return 1<=x&&x<=n&&1<=y&&y<=n;
}
int bfs(){
    int cnt=0;
    for (int i=1;i<=n;++i){
        for (int j=1;j<=n;++j){
            if (c[i][j]=='#'&&(!vst[i][j])){
                bool flag=false;
                q.push((node){i,j});
                while (!q.empty()){
                    node u=q.front();q.pop();
                    int x=u.x,y=u.y;vst[x][y]=1;
                    if (l[x][y]) flag=true;
                    for (int k=1;k<=4;++k){
                        int prex=x+dx[k],prey=y+dy[k];
                        if (vaild(prex,prey)&&(!vst[prex][prey])&&(c[prex][prey]=='#')) q.push((node){prex,prey});
                    }
                }
                if (!flag) ++cnt;
            //  cout<<i<<" "<<j<<" "<<flag<<endl;
            }
        }
    }
    return cnt;
}
int main(){
    cin>>n;for (int i=1;i<=n;++i) for (int j=1;j<=n;++j) cin>>c[i][j];
    for (int i=1;i<=n;++i){
        for (int j=1;j<=n;++j){
            int x=i,y=j;
            l[x][y]=(c[i][j]=='#');
            if (c[x][y]=='#'){
                for (int k=1;k<=4;++k){
                    int prex=x+dx[k],prey=y+dy[k];
                    if (!(vaild(prex,prey))) continue;
                    if (c[prex][prey]=='.') l[x][y]=0;
                }
            }
            //cout<<l[x][y];
        }
        //cout<<endl;
    }
    cout<<bfs()<<endl;
    return 0;
}

by gaojizhe05 @ 2024-01-31 19:41:27

@Bingxiu 类似01迷宫的板子题


上一页 |