洛谷 P1141 【bfs染色】

题目链接

 

 

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

#define rep(i,s,t) for(int i=s;i<t;i++)
#define REP(i,s,t) for(int i=s;i<=t;i++)
const int N = 1e3 + 5;
int n, m, color, vis[N][N];
char g[N][N];
const int dir[][2] = {1,0,0,1,-1,0,0,-1};
int ans[1000010];     //最多可能有1000*1000个联通块

struct Node { int x, y; };
queue<Node>q;

void bfs(int row, int col) {
    Node now, next;
    now.x = row, now.y = col;
    vis[row][col] = color;
    ans[color]++;
    q.push(now);
    while(!q.empty()){
        now = q.front(); q.pop();
        rep(i,0,4) {
            int nx = now.x + dir[i][0];
            int ny = now.y + dir[i][1];
            if(nx < 1 || nx > n || ny < 1 || ny > n || vis[nx][ny] || g[now.x][now.y] == g[nx][ny]) continue;
            vis[nx][ny] = color; ans[color]++;
            next.x = nx, next.y = ny;
            q.push(next);
        }
    }
}

int main() {
    scanf("%d %d", &n, &m);
    REP(i,1,n) scanf("%s", g[i] + 1);
    REP(i,1,m) {
        int x, y; scanf("%d%d",&x,&y);
        if(!vis[x][y]) {
            color = i;
            while(!q.empty()) q.pop();
            bfs(x,y);
        }
        printf("%d\n", ans[vis[x][y]]);
    }
    return 0;
}

 

 

 

2018-06-01

posted @ 2018-06-01 18:41  悠悠呦~  阅读(272)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end