40分求调

P1141 01迷宫

jfls211320zhr @ 2024-07-20 20:40:54

#include<bits/stdc++.h>
using namespace std;
int a[1004][1004];
int n,m,cx,cy;
string s;
bool vis[1004][1004];
int cnt;
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
void dfs(int x,int y){
    int xx,yy;
    for(int i=0;i<4;i++){
        xx=x+dx[i];
        yy=y+dy[i];
        if(xx&&yy&&xx<=n&&yy<=n&&a[xx][yy]!=a[x][y]&&!vis[xx][yy]){
            vis[xx][yy]=1;
            dfs(xx,yy);
            cnt++;
        }
    }
}
int main(){
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++){
        cin>>s;
        for(int ii=1;ii<=n;ii++)a[i][ii]=s[ii-1]-48;
    }
    while(m--){
        memset(vis,0,sizeof(vis));
        cnt=0;
        scanf("%d %d",&cx,&cy);
        dfs(cx,cy);
        printf("%d\n",cnt);
    }
    return 0;
}

|