http://acm.hdu.edu.cn/showproblem.php?pid=1175
一道ACM题目,方法很经典,源码如下:
#include<iostream>
#include<queue>
using namespace std;
int h[1005][1005];
int v[1005][1005];
int n,m,w,win;
struct node{int x,y,flag,step;};
queue <node> que;
node temp,tmp;
int mov[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int run(int a,int b,int c,int d)
{
int i,x,y;
memset(v,-1,sizeof(v));
while(!que.empty())que.pop();
for(i=0;i<4;i++){
temp.x=a;
temp.y=b;
temp.flag=i;
temp.step=0;
que.push(temp);}
while(!que.empty())
{
tmp=que.front();
que.pop();
for(i=0;i<4;i++)
{
x=tmp.x+mov[i][0];
y=tmp.y+mov[i][1];
if(x==c&&y==d)
{
if(i!=tmp.flag&&tmp.step>=2)continue;
win=1;return 0;
}
if(h[x][y]==0&&x<=n&&x>=1&&y<=m&&y>=1)
{
if(i==tmp.flag&&(v[x][y]==-1||v[x][y]>=tmp.step))
{
temp.x=x;
temp.y=y;
temp.step=tmp.step;
temp.flag=i;
v[x][y]=temp.step;
que.push(temp);
}
else if(tmp.step<2&&(v[x][y]==-1||v[x][y]>=tmp.step+1))
{
temp.x=x;
temp.y=y;
temp.step=tmp.step+1;
temp.flag=i;
v[x][y]=temp.step;
que.push(temp);
}
}
}
}
return 0;
}
int main()
{
int i,j,a,b,c,d;
while(scanf("%d%d",&n,&m)&&n)
{
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&h[i][j]);
scanf("%d",&w);
while(w--)
{
win=0;
scanf("%d%d%d%d",&a,&b,&c,&d);
if(h[a][b]!=h[c][d]||h[a][b]==0||(a==c&&b==d)){printf("NO/n");continue;}
run(a,b,c,d);
if(win==1)printf("YES/n");
else printf("NO/n");
}
}
return 0;
}