Files
ClassFeedback/C++代码/学习/01迷宫.cpp

71 lines
1.1 KiB
C++

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int n, m, x, y;
int cntt[1010][1010];
char arr[1010][1010];
int tot = 0;
int sz[1000010];
int fx[] = {0, 0, 1, 0, -1};
int fy[] = {0, 1, 0, -1, 0};
int q[1000010][3];
void bfs(int x, int y){
int cnt = 1;
tot++;
q[1][1] = x;
q[1][2] = y;
cntt[x][y] = tot;
int head = 1, tail = 1;
while(head <= tail){
int cx = q[head][1];
int cy = q[head][2];
int tx, ty;
for(int i = 1; i <= 4; i++){
tx = cx + fx[i];
ty = cy + fy[i];
if(tx >= 1 && tx <= n && ty >= 1 && ty <= n && cntt[tx][ty] == 0
&& (arr[cx][cy] != arr[tx][ty])){
tail++;
q[tail][1] = tx;
q[tail][2] = ty;
cntt[tx][ty] = tot;
// cout << "ÎÒ¿ÉÒÔÀ´";
cnt++;
}
}
head++;
}
sz[tot] = cnt;
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
cin >> arr[i][j];
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(cntt[i][j] == 0) bfs(i, j);
}
}
for(int i = 1; i <= m; i++){
cin >> x >> y;
cout << sz[cntt[x][y]] << endl;
}
return 0;
}