P1141 01迷宫 80分TLE求调

P1141 01迷宫

ethan20242024 @ 2024-09-02 20:05:41

#include <bits/stdc++.h>
using namespace std;

int n, m, a[1005][1005], memo[1005][1005];
int dxy[4][4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
bool vis[1005][1005];
struct Node {
    int x, y;
    Node(int x, int y) : x(x), y(y) {}
};

int bfs(int sx, int sy) {
    if (memo[sx][sy] != -1) return memo[sx][sy];

    queue<Node> q;
    int ans = 0;

    vis[sx][sy] = 1;
    q.push(Node(sx, sy));
    while (!q.empty()) {
        Node tmp = q.front();
        int fx = tmp.x;
        int fy = tmp.y;
        q.pop();

        for (int i = 0; i < 4; i++) {
            int xx = fx + dxy[i][0];
            int yy = fy + dxy[i][1];
            if (xx < 1 || xx > n || yy < 1 || yy > n) continue;
            if (a[xx][yy] != a[fx][fy] && vis[xx][yy] == 0) {
                vis[xx][yy] = 1;
                ans++;
                q.push(Node(xx, yy));
            }
        }
    }
    ans++;
    for (int i=1;i<=n;i++){
        for (int j=1;j<=n;j++){
            if (vis[i][j] == 1){
                memo[i][j] = ans;
                vis[i][j] = 0;
            }
        }
    }
    return ans;
}

int main(){
    memset(memo, -1, sizeof(memo));
    memset(vis, 0, sizeof(vis));
    scanf("%d %d", &n, &m);

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            char tmp;
            scanf(" %c", &tmp);
            a[i][j] = tmp - '0';
        }
    }

    for (int t = 0; t < m; t++) {
        int x, y;
        scanf("%d %d", &x, &y);
        printf("%d\n", bfs(x, y));
    }

    return 0;
}

|