70pts TLE求助

P1141 01迷宫

SANJIAOJIE @ 2024-11-03 11:05:06

#include<bits/stdc++.h>
using namespace std;
const int N=1e3+10;
int n,q,x,y,ans;
char a[N][N];bool f[N][N];
int fx[5]={0,1,-1,0,0};
int fy[5]={0,0,0,1,-1};
int dfs(int x,int y,char c){
    for(int i=1;i<=4;i++){
        int tx=x+fx[i],ty=y+fy[i];
        if(tx>=1&&ty>=1&&tx<=n&&ty<=n&&f[tx][ty]==false){
            if(c=='0'&&a[tx][ty]=='1'){
                ans++;
                f[tx][ty]=true;
                dfs(tx,ty,a[tx][ty]);
            }
            if(c=='1'&&a[tx][ty]=='0'){
                ans++;
                f[tx][ty]=true;
                dfs(tx,ty,a[tx][ty]);
            }
        }
    }
    return ans;
}
int main(){
    cin>>n>>q;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>a[i][j];
        }
    }
    while(q--){
        cin>>x>>y;
        memset(f,false,sizeof(f));
        ans=1;
        f[x][y]=true;
        cout<<dfs(x,y,a[x][y])<<"\n";
    }
    return 0;
}

by chenxitao @ 2024-11-03 11:09:44

#include<cstdio>
#include<cstring>
int n,m,ans[100002],x,y,f[1002][1002];
char s[1002][1002];
void dfs(int r,int c,int z,int lll){
    if (r<0 || r>=n || c<0 || c>=n || f[r][c]!=-1 || s[r][c]-'0'!=z)return;
    f[r][c]=lll;ans[lll]++;
    dfs(r-1,c,!z,lll);dfs(r+1,c,!z,lll);dfs(r,c-1,!z,lll);dfs(r,c+1,!z,lll);
}
int main(){
    scanf("%d%d",&n,&m);
    for (int i=0;i<n;i++)
    scanf("%s",s[i]);
    memset(f,-1,sizeof(f));
    for (int i=0;i<m;i++){
        scanf("%d%d",&x,&y);x--;y--;
        if(f[x][y]==-1)dfs(x,y,s[x][y]-'0',i);else ans[i]=ans[f[x][y]];
    }
    for (int i=0;i<m;i++)
    printf("%d\n",ans[i]);
    return 0;
}

求关


by niuniudundun @ 2024-11-03 11:15:47

@chenxitao 你这是题解吧


by chenxitao @ 2024-11-03 11:31:04

?我老师给的思路我自己写的啊!


by SANJIAOJIE @ 2024-11-09 19:09:06

@chenxitao 我被老师喊去讲课用的。


by shx2011 @ 2024-11-09 23:28:29

@SANJIAOJIE 盲猜正解剪枝


|