aleavf @ 2024-06-05 08:44:35
#include<bits/stdc++.h>
using namespace std;
long long a[1100][1100],e[1100][1100];
long long ans[100000],w=2,b[1000000];
int c,d,q,p;
void dfs(int x,int y){
if(e[x][y]!=0||x>c||y>c||x<1||y<1) return;
e[x][y]=w;
ans[w]++;
if(max(a[x][y],a[x+1][y])-min(a[x][y],a[x+1][y])==1) dfs(x+1,y);
if(max(a[x-1][y],a[x][y])-min(a[x][y],a[x-1][y])==1) dfs(x-1,y);
if(max(a[x][y],a[x][y+1])-min(a[x][y],a[x][y+1])==1) dfs(x,y+1);
if(max(a[x][y-1],a[x][y])-min(a[x][y],a[x][y-1])==1) dfs(x,y-1);
}
int main() {
char s;
scanf("%d%d",&c,&d);
for(int i = 1;i <= c;++i)
for(int j = 1;j <= c;++j){
cin>>s;
a[i][j]=s-'0';}
for(int i = 1;i <= c;++i)
for(int j = 1;j <= c;++j)
if(e[i][j]<2){
dfs(i,j);
++w;
}
while(d--){
scanf("%d%d",&q,&p);
printf("%lld",ans[e[q][p]]);
printf("\n");
}
}