90分TLE求调

P1141 01迷宫

Yeonjun_0913 @ 2024-10-19 09:29:20

RT

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

const int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int n,m,tmp;
int ans[1005][1005],f[1000000][2];
bool a[1005][1005],vis[1005][1005];
void dfs(int x,int y){
    for (int i=0;i<4;i++){
        int xx=x+dir[i][0],yy=y+dir[i][1];
        if (xx<=n&&yy<=n&&xx>0&&yy>0){
            if (a[xx][yy]==!a[x][y]&&!vis[xx][yy]){
                vis[xx][yy]=true;
                f[tmp][0]=xx,f[tmp][1]=yy;
                tmp++;
                dfs(xx,yy);
            }
        }
    }
}

int main (){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    string s;
    for (int i=1;i<=n;i++){
        cin >> s;
        for (int j=0;j<s.size();j++){
            a[i][j+1]=s[j]-'0';
        }
    }
    int sx,sy;
    for (int l=0;l<m;l++){
        cin >> sx >> sy;
        if (ans[sx][sy]!=0){
            cout << ans[sx][sy] << endl;
            continue;
        }
        memset(vis,0,sizeof(vis));
        tmp=0;
        f[tmp][0]=sx,f[tmp++][1]=sy;
        vis[sx][sy]=true;
        dfs(sx,sy);
        for (int i=0;i<tmp;i++){
            if (f[i][0]<=n&&f[i][1]<=n&&f[i][0]>0&&f[i][1]>0){
                ans[f[i][0]][f[i][1]]=max(ans[f[i][0]][f[i][1]],tmp);
            }
        }
        cout << ans[sx][sy] << endl;
    }
    return 0;
}

by LEOOOOOOOOO @ 2024-10-19 10:49:34

可以使用bfs


|