70分求调

P1141 01迷宫

ChasonWang @ 2024-10-07 00:14:09

RT

#include<bits/stdc++.h>
using namespace std;
int n,m,tx,ty,dx[]={0,-1,1,0,0},dy[]={0,0,0,1,-1},cnt,ans[1005][1005];
bool v[1005][1005];
char a[1005][1005];
void dfs(int x,int y){
    if(v[x][y])return;
    v[x][y]=1;
    cnt++;
    for(int i=1;i<=4;i++){
        if(a[x+dx[i]][y+dy[i]]==a[x][y]||x+dx[i]>n||y+dy[i]>n||x+dx[i]<1||y+dy[i]<1)continue;
        dfs(x+dx[i],y+dy[i]);
    }
}
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>a[i][j];
        }
    }
    memset(ans,-1,sizeof(ans));
    while(m--){
        cnt=0;
        memset(v,0,sizeof(v));
        cin>>tx>>ty;
        if(ans[tx][ty]!=-1){
            cout<<ans[tx][ty]<<endl;
            continue;
        }
        dfs(tx,ty);
        cout<<cnt<<endl;
        ans[tx][ty]=cnt;
    }
    return 0; 
}

|