只要该地块处于同一个连通块内,那么必然可以相互到达。
那么查询的结果,就是该地块 (x,y) 所在的连通块的大小。
所以使用一个blockNum 来表是连通块的大小
dfs 代码
#include<iostream>
using namespace std;
const int MAXN = 1005;
const int dirs[][2] = {{-1,0},{1,0},{0,1},{0,-1}};
char grid[MAXN][MAXN];
//每个点(x,y)的blockId
int blockIds[MAXN][MAXN];
//block的大小
int blockNum[MAXN * MAXN];
int block;
int n,m;
bool inArea(int x,int y){
return x >= 1 && x <= n && y >= 1 && y <= n;
}
void dfs(int x,int y){
for(auto &d : dirs){
int nx = x + d[0];
int ny = y + d[1];
if(inArea(nx,ny) && !blockIds[nx][ny] &&
grid[x][y] ^ grid[nx][ny]){
blockIds[nx][ny] = block;
blockNum[block]++;
dfs(nx,ny);
}
}
}
int main(){
cin >> n >> m;
for(int i = 1;i <= n;i++){
cin >> grid[i] + 1;
}
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
if(!blockIds[i][j]){
block++;
blockIds[i][j] = block;
blockNum[block]++;
dfs(i,j);
}
}
}
int qx,qy;
for(int i = 1;i <= m;i++){
cin >> qx >> qy;
cout << blockNum[blockIds[qx][qy]] << endl;
}
return 0;
}
bfs 代码
#include<iostream>
#include<queue>
using namespace std;
using PII = pair<int,int>;
const int MAXN = 1005;
const int dirs[][2] = {{-1,0},{1,0},{0,1},{0,-1}};
char grid[MAXN][MAXN];
//每个点(x,y)的blockId
int blockIds[MAXN][MAXN];
//block的大小
int blockNum[MAXN * MAXN];
int block;
int n,m;
bool inArea(int x,int y){
return x >= 1 && x <= n && y >= 1 && y <= n;
}
void bfs(int x,int y){
queue<PII> q;
q.push({x,y});
while(!q.empty()){
auto cur = q.front();
q.pop();
for(auto &d : dirs){
int nx = cur.first + d[0];
int ny = cur.second + d[1];
if(inArea(nx,ny) && !blockIds[nx][ny] &&
grid[cur.first][cur.second] ^ grid[nx][ny]){
blockIds[nx][ny] = block;
blockNum[block]++;
q.push({nx,ny});
}
}
}
}
int main(){
cin >> n >> m;
for(int i = 1;i <= n;i++){
cin >> grid[i] + 1;
}
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
if(!blockIds[i][j]){
block++;
blockIds[i][j] = block;
blockNum[block]++;
bfs(i,j);
}
}
}
int qx,qy;
for(int i = 1;i <= m;i++){
cin >> qx >> qy;
cout << blockNum[blockIds[qx][qy]] << endl;
}
return 0;
}