70分,TLE,蒟蒻求助

P1141 01迷宫

xiexiaoyuawa @ 2024-04-08 12:32:56

bfs写的, #1 #6 #7 #11 TLE

#include <iostream>
#include <queue>

using namespace std;

const int maxn = 1010;
int n, m;
char a[maxn][maxn];
bool vis[maxn][maxn];
struct coord{
    int x, y;
};
queue <coord> q;
const int dirs[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int ans;

bool match(coord node1, coord node2){
    if(a[node1.y][node1.x] == '1' && a[node2.y][node2.x] == '0') return 1;
    if(a[node1.y][node1.x] == '0' && a[node2.y][node2.x] == '1') return 1;
    return 0;
}

int main(){
    cin >> n >> m;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            cin >> a[i][j];
        }
    }
    while(m--){
        ans = 1;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                vis[i][j] = 0;
            }
        }
        int ii, jj;
        cin >> ii >> jj;
        ii--, jj--;
        vis[ii][jj] = 1;
        coord node;
        node.x = jj, node.y = ii;
        q.push(node);
        while(!q.empty()){
            coord now = q.front();
            q.pop();
            for(int i = 0; i < 4; i++){
                int nextx = now.x + dirs[i][0];
                int nexty = now.y + dirs[i][1];
                if(nextx >= 0 && nexty >= 0 && nextx < n && nexty < n){
                    if(!vis[nexty][nextx] && match(now, (coord){nextx, nexty})){
                        vis[nexty][nextx] = 1;
                        q.push((coord){nextx, nexty});
                        ans++;
                    }
                }
            }
        }
        cout << ans << '\n';
    }
    return 0;
}

by cgxd @ 2024-04-26 19:13:07

我也遇到了这个情况,Devc++上运行了好几分钟才运行完


|