并查集:
#include<cstdio>
#define N 505
using namespace std;
struct node
{
int x,y;
};
char map[N][N];
node p[N*N];
int turnx[4]={0,0,-1,1};
int turny[4]={-1,1,0,0};
int father[N*N];
int rank[N*N];
int find(int x)
{
if(father[x]!=x)
father[x]=find(father[x]);
return father[x];
}
void connect(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
if(rank[a]>rank[b])
father[b]=a;
else if(rank[a]<rank[b])
father[a]=b;
else
{
father[a]=b;
rank[b]++;
}
}
}
int main()
{
int T;
int i,j;
int n,m,q;
int china,india;
int dx,dy;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
scanf("%s",map[i]+1);
scanf("%d",&q);
for(i=1;i<=q;i++)
{
scanf("%d%d",&p[i].x,&p[i].y);
++p[i].x,++p[i].y;
map[p[i].x][p[i].y]='1';
}
for(i=1;i<=n*m+2;i++)
{
father[i]=i;
rank[i]=0;
}
china=n*m+1;
india=n*m+2;
for(i=1;i<=m;i++)
{
if(map[1][i]=='0')
connect(i,china);
if(map[n][i]=='0')
connect((n-1)*m+i,india);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(map[i][j]=='0')
{
if(i<n&&map[i+1][j]=='0')
connect(i*m+j,(i-1)*m+j);
if(j<m&&map[i][j+1]=='0')
connect((i-1)*m+j+1,(i-1)*m+j);
}
}
}
if(find(china)==find(india))
{
printf("-1\n");
continue;
}
for(i=q;i>0;i--)
{
map[p[i].x][p[i].y]='0';
if(p[i].x==1)
connect(p[i].y,china);
if(p[i].x==n)
connect((n-1)*m+p[i].y,india);
for(j=0;j<4;j++)
{
dx=p[i].x+turnx[j];
dy=p[i].y+turny[j];
if(dx>0&&dx<=n&&dy>=0&&dy<=m&&map[dx][dy]=='0')
connect((dx-1)*m+dy,(p[i].x-1)*m+p[i].y);
}
if(find(china)==find(india))
break;
}
printf("%d\n",i);
}
return 0;
}
BFS+二分:
#include<cstdio>
#include<queue>
#include<cstring>
#include<stack>
using namespace std;
int n,m;
char map[510][510];
int visit[510][510];
int turnx[4]={1,-1,0,0};
int turny[4]={0,0,1,-1};
struct node
{
int x;
int y;
};
node u[300000];
int yes(int x,int y)
{
if(x<0||y<0||x>n+1||y>=m||map[x][y]=='1')
return 0;
return 1;
}
queue<node> s;
int bfs()
{
int i;
node p,q;
p.x=0;
p.y=0;
visit[p.x][p.y]=1;
s.push(p);
while(!s.empty())
{
p=s.front();
s.pop();
if(p.x==n+1&&p.y==0)
{
while(!s.empty())
s.pop();
return 1;
}
for(i=0;i<4;i++)
{
q=p;
q.x+=turnx[i];
q.y+=turny[i];
if(!visit[q.x][q.y]&&yes(q.x,q.y))
{
visit[q.x][q.y]=1;
s.push(q);
}
}
}
return 0;
}
int main()
{
int T,Q,i,begin,end,mid;
scanf("%d",&T);
while(T--)
{
while(!s.empty())
s.pop();
scanf("%d%d",&n,&m);
for(i=0;i<m;i++)
{
map[0][i]='0';
map[n+1][i]='0';
}
memset(visit,0,sizeof(visit));
for(i=1;i<=n;i++)
scanf("%s",map[i]);
scanf("%d",&Q);
for(i=1;i<=Q;i++)
{
scanf("%d%d",&u[i].x,&u[i].y);
++u[i].x;
}
begin=1;
end=Q;
while(begin<=end)
{
mid=(begin+end)/2;
memset(visit,0,sizeof(visit));
for(i=begin;i<=mid;i++)
map[u[i].x][u[i].y]='1';
for(i=mid+1;i<=end;i++)
map[u[i].x][u[i].y]='0';
if(bfs()==1)
begin=mid+1;
else
end=mid;
if(begin==end)
{
mid=begin;
break;
}
}
printf("%d\n",mid);
}
return 0;
}