洛谷 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
作者:is_ok
出处:http://www.cnblogs.com/00isok/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。