lhs_chris @ 2023-11-29 11:42:25
#include<bits/stdc++.h>
#include<cstring>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#include<map>
#define ll long long
using namespace std;
const int N=1e5+10;
const int M=2023;
const int inf=0x3f3f3f3f;
int n,m,a[2000][2000],vis[2000][2000],viss[2000][2000];
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
struct node
{
int x,y,num,s;
};
struct abc
{
int xxx,yyy;
}v[2000][2000];
int bfs(int xx,int yy)
{
// memset(vis,0,sizeof vis);
vis[xx][yy]=1;
queue<node> q;
while(q.size())
{
q.pop();
}
int ans=1;
q.push(node{xx,yy,1,a[xx][yy]});
while(q.size())
{
node now=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int nx=dx[i]+now.x;
int ny=dy[i]+now.y;
if(((now.s==0 and a[nx][ny]==1) or (now.s==1 and a[nx][ny]==0)) and vis[nx][ny]==0 and nx>=1 and nx<=n and ny>=1 and ny<=n)
{
vis[nx][ny]=1;
if(v[nx][ny].xxx==-1 and v[nx][ny].yyy==-1)
{
v[nx][ny].xxx=xx;//把路径上的点全部标记为 当前点的儿子,是儿子的最后可以直接输出父亲的答案
v[nx][ny].yyy=yy;
}
ans++;
q.push(node{nx,ny,now.num+1,a[nx][ny]});
}
}
}
viss[xx][yy]=ans;
return ans;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
char xx;
cin>>xx;
a[i][j]=xx;
a[i][j]-=48;
v[i][j].xxx=-1;
v[i][j].yyy=-1;
}
}
int xy,yx;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&xy,&yx);
(v[xy][yx].xxx==-1 and v[xy][yx].yyy==-1) ? printf("%d\n",bfs(xy,yx)) : printf("%d\n",viss[v[xy][yx].xxx][v[xy][yx].yyy]);
//连通块优化一下
//搜索过的就直接输出,否则去搜索
}
return 0;
}
现在是WA 60% 但是 把bfs 里面的memset 注释删掉就是TLE 80% 了