#include <iostream>
#include <cstring>
using namespace std;
const int N = 1010, M = 1e5 + 10;
int q[N][N], n, m, cnt, lin[N * N+10];
int idx = 1;
bool st[N][N];
int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
int dfs(int x, int y)
{
st[x][y] = true;
int sum = 1;
lin[n * x + y] = idx;
for (int i = 0; i < 4; i++)
{
int a = x + dx[i], b = y + dy[i];
if (a > 0 && a <= n && b > 0 && b <= n && (q[a][b] == !q[x][y]) && st[a][b] == false)
{
int s = dfs(a, b);
sum += s;
}
}
cnt = max(cnt, sum);
return sum;
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
string s;
cin >> s;
for (int j = 1; j <= n; j++)
{
q[i][j] = s[j-1] - '0';
}
getchar();
}
int res[M];
while (m--)
{
int i, j;
cin >> i >> j;
if(lin[n*i+j] == 0)
{
cnt = 0;
memset(st, false, sizeof(st));
dfs(i, j);
res[idx++] = cnt;
cout << cnt << endl;
}
else
{
cout << res[lin[n * i + j]] << endl;
}
}
return 0;
}
是哪里优化的还不够吗?