90分求助
  • 板块P1141 01迷宫
  • 楼主un_dauant
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/2/20 15:28
  • 上次更新2023/10/24 00:15:52
查看原帖
90分求助
341644
un_dauant楼主2023/2/20 15:28
#include <algorithm>
#include<bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <queue>
#include <string>
using namespace std;
const int N = 1005;
int n , m; 
char g[N][N];
int mem[N][N];
typedef pair<int , int >PII;
bool vis[N][N];
queue<PII> que,que1;
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};
int bfs(int x , int y){
    int cnt = 1;
    // 每一次 bfs
    vis[x][y] = true;
    memset(vis,false, sizeof(vis));
    que.push({x,y});

    while(!que.empty()){
        PII t = que.front();
        que1.push(t); //记录que队列中遍历过的点,方便以后染色
        que.pop();
        for(int i = 0 ; i < 4 ;i++){
            int xx = t.first + dx[i] , yy = t.second + dy[i];
            if(((g[t.first][t.second] == '0' && g[xx][yy] == '1') || (g[t.first][t.second] == '1' && g[xx][yy]== '0'))&& (xx >= 1 && xx <= n && yy >=1 && yy <=n) && (!vis[xx][yy]))
            {
                que.push({xx,yy});
                cnt++;
                vis[xx][yy] = true;
            }
        }
    }    
    PII temp ;
    while(!que1.empty()){     //染色
        temp = que1.front();
        que1.pop();
        mem[temp.first][temp.second] = cnt;
    }
    return cnt;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin >> n >> m;

    for(int i = 1 ; i <= n;i++){
        for(int j = 1 ;j<=n;j++){
            cin >> g[i][j];
        }
    }
    int x , y;
    while(m--){
        cin >> x >> y;
        if(mem[x][y]!=0) cout << mem[x][y]<<"\n";
        else{
            int result = bfs(x, y);
            cout << result << "\n";
        }
    }
    return 0;
}
2023/2/20 15:28
加载中...