70分 TLE了 大佬看看这怎么改呀

P1141 01迷宫

Happiness_3 @ 2024-11-13 21:11:13

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll N = 1e3 + 10;
ll n,m;
ll g[N][N];
bool vis[N][N];
ll dis[N][N];
ll dx[] = {1,-1,0,0} , dy[] = {0,0,-1,1};

signed main(){
    cin >> n >> m;
    for(ll i = 1 ; i <= n ; ++i){
        for(ll j = 1 ; j <= n ; ++j){
            char ch;
            cin >> ch;
            if(ch == '0') g[i][j] = 0;
            if(ch == '1') g[i][j] = 1;
        }
    }

    while(m--){
        memset(vis , 0 , sizeof(vis));
        ll x,y;
        cin >> x >> y;

        queue<pair<ll,ll>> q;
        q.push({x,y});
        vis[x][y] = 1;
        ll cnt = 1;
        while(q.size()){
            auto t = q.front();
            q.pop();
            for(ll k = 0 ; k < 4 ; ++k){
                ll tx = t.first + dx[k] , ty = t.second + dy[k];
                if(tx < 1 || tx > n || ty < 1 || ty > n) continue;
                if(vis[tx][ty] == 1) continue;
                if(g[tx][ty] == 1 && g[t.first][t.second] == 1) continue;
                if(g[tx][ty] == 0 && g[t.first][t.second] == 0) continue;
                q.push({tx,ty});
                vis[tx][ty] = 1;
                cnt ++;
            }
        }
        cout << cnt << endl;
    }
}

by WuJiaNuo19 @ 2024-11-13 21:21:42

@Happiness_3 哥们儿看题解。要染色。


by Happiness_3 @ 2024-11-13 21:28:56

@WuJiaNuo19 好的好的 谢谢!


|