70分TLE求调

P1141 01迷宫

huzixiao @ 2024-12-29 12:11:13

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int n, m;
string map[1005];
bool vis[1005][1005];
bool in(int x, int y) {
    return x >= 1 && x <= n && y >= 1 && y <= n;
}
struct node {
    int x, y, step;
};
int bfs(int x, int y) {
    int cnt = 1;
    queue<node> q;
    vis[x][y] = true;
    q.push({x, y, 1});
    const int next[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    while (!q.empty()) {
        node now = q.front();
        q.pop();
        for (int i = 0; i < 4; i++) {
            int tx = now.x + next[i][0];
            int ty = now.y + next[i][1];
            if (!vis[tx][ty] && in(tx, ty) && map[now.x][now.y] != map[tx][ty]) {
                vis[tx][ty] = true;
                cnt++;
                q.push({tx, ty, now.step + 1});
            }
        }
    }
    return cnt;
}
int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> map[i];
        map[i].insert(0, " ");
    }
    while (m--) {
        int x, y;
        cin >> x >> y;
        cout << bfs(x, y) << endl;
        memset(vis, false, sizeof vis);
    }
    return 0;
}

|