求调
#include <bits/stdc++.h>
#define maxn 1010
using namespace std;
const int walk[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int n, m;
int M[maxn][maxn];
bool vis[maxn][maxn]; // 标记是否访问过
int ans[maxn][maxn]; // 记忆化
int change(char ch)
{
if (ch == '0')
return 0;
return 1;
}
int main()
{
ios::sync_with_stdio(false); // 加速读入
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
char ch;
cin >> ch;
// 映射
M[i][j] = change(ch);
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
ans[i][j] = 1;
}
}
for (int I = 1; I <= m; I++)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
vis[i][j] = 0;
}
}
int x, y;
cin >> x >> y;
queue<pair<int, int>> q;
q.push(make_pair(x, y));
vis[x][y] = 1;
// 如果之前搜过,直接输出答案
if (ans[x][y] != 1)
{
cout << ans[x][y] << endl;
continue;
}
// bfs
while (!q.empty())
{
int nx = q.front().first, ny = q.front().second;
q.pop();
for (int i = 0; i < 4; i++)
{
int dx = nx + walk[i][0], dy = ny + walk[i][1];
if (dx > n || dy > n || dx < 1 || dy < 1)
continue;
if (M[nx][ny] == M[dx][dy] || vis[dx][dy])
continue;
vis[dx][dy] = 1;
q.push(make_pair(dx, dy));
ans[x][y]++;
}
}
cout << ans[x][y] << endl;
}
return 0;
}