dfs暴搜TLE+WA悬棺求调

P1141 01迷宫

wky_wsy @ 2024-11-03 09:53:55

#include <bits/stdc++.h>
#define int long long
using namespace std;
int n,m;
char a[1010][1010];
int dfs(int x,int y,int g){
    if(x>=1&&x<=n&&y>=1&&y<=n){
        if(a[x][y]!=a[x][y+1]) return dfs(x,y+1,g+1);
        else if(a[x][y]!=a[x+1][y]) return dfs(x+1,y,g+1);
        else if(a[x][y]!=a[x][y-1]) return dfs(x,y-1,g+1);
        else if(a[x][y]!=a[x-1][y]) return dfs(x-1,y,g+1);
        else return g;
    }
    else{
        return g;
    }
}
signed main(){
    scanf("%lld%lld",&n,&m);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            scanf("%c",&a[i][j]);
        }
    }
    while(m--){
        int x,y,g=0;
        scanf("%lld%lld",&x,&y);
        int z=dfs(x,y,g);
        printf("%lld\n",z);
    }
}

by XCJHYJ @ 2024-11-05 21:01:39

一看就知道该用BFS啊...


|