因为各种乱七八糟的原因,学搜索实在是学了太久了也咕了好久博客啊。准备再做一遍之前写过的题顺便补一下博客qwq
01迷宫
【题目链接】(https://www.luogu.org/problemnew/show/P1141)
这道题LITTLESUN用的是一个联通块的bfs
中间出了一些锅
- 因为有多组数据cnt一定要记得清零·
- 这一句很重要
if(done[r.x][r.y] != 0) continue;
因为除了在特判时保证访问过的不再次被添加到队列中,还要保证一个点可能在它被使用之前被添加了多次。 - 记得看好数据范围数组不要过大或者过小
- 在每次 bfs前多加一个特判如果这个点在之前访问过的联通块中就不需要在进行bfs由此来保证复杂度。
AC代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#define MAXN 1010
#define MEXN 5000000
using namespace std;
int n,m;
int x,y;
int G[MAXN][MAXN];
int done[MAXN][MAXN];
int num[MEXN];
int color=1;
int cnt=0;
struct item
{
int x;
int y;
};
queue <item>q;
void bfs(item t)
{
q.push(t);
while(!q.empty())
{
item r;
r=q.front();
q.pop();
if(done[r.x][r.y] != 0) continue;
done[r.x][r.y]=color;
cnt++;
if(G[r.x][r.y]==0)
{
if(G[r.x+1][r.y]==1&&r.x+1<=n&&done[r.x+1][r.y]==0)
{
item t2;
t2.x=r.x+1;
t2.y=r.y;
//printf("x:%d,y:%d
",t2.x,t2.y);
q.push(t2);
}
if(G[r.x-1][r.y]==1&&r.x - 1>=1&&done[r.x-1][r.y]==0)
{
item t2;
t2.x=r.x-1;
t2.y=r.y;
//printf("x:%d,y:%d
",t2.x,t2.y);
q.push(t2);
}
if(G[r.x][r.y+1]==1&&r.y + 1<=n&&done[r.x][r.y+1]==0)
{
item t2;
t2.x=r.x;
t2.y=r.y+1;
//printf("x:%d,y:%d
",t2.x,t2.y);
q.push(t2);
}
if(G[r.x][r.y-1]==1&&r.y - 1>=1&&done[r.x][r.y-1]==0)
{
item t2;
t2.x=r.x;
t2.y=r.y-1;
// printf("x:%d,y:%d
",t2.x,t2.y);
q.push(t2);
}
}
if(G[r.x][r.y]==1)
{
if(G[r.x+1][r.y]==0&&r.x + 1<=n&&done[r.x+1][r.y]==0)
{
item t2;
t2.x=r.x+1;
t2.y=r.y;
//printf("x:%d,y:%d
",t2.x,t2.y);
q.push(t2);
}
if(G[r.x-1][r.y]==0&&r.x - 1>=1&&done[r.x-1][r.y]==0)
{
item t2;
t2.x=r.x-1;
t2.y=r.y;
//printf("x:%d,y:%d
",t2.x,t2.y);
q.push(t2);
}
if(G[r.x][r.y+1]==0&&r.y + 1<=n&&done[r.x][r.y+1]==0)
{
item t2;
t2.x=r.x;
t2.y=r.y+1;
//printf("x:%d,y:%d
",t2.x,t2.y);
q.push(t2);
}
if(G[r.x][r.y-1]==0&&r.y - 1>=1&&done[r.x][r.y-1]==0)
{
item t2;
t2.x=r.x;
t2.y=r.y-1;
//printf("x:%d,y:%d
",t2.x,t2.y);
q.push(t2);
}
}
}
num[color]=cnt;
}
int main()
{
//freopen("ss.txt","r",stdin);
scanf("%d%d",&n,&m);
for(int j=1;j<=n;j++)
{
for(int k=1;k<=n;k++)
{
char c;
cin>>c;
G[j][k]=c-'0';
}
}
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
item t;
t.x=x;
t.y=y;
if(done[x][y]!=0)
{
int ans;
ans=done[x][y];
printf("%d
",num[ans]);
}
else
{
color++;
cnt = 0;
bfs(t);
printf("%d
",num[color]);
}
}
return 0;
}