HDU 1175
简单 BFS
/*************************************************************************
> File Name: 1.cpp
> Author:yuan
> Mail:
> Created Time: 2014年11月25日 星期二 19时40分03秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int maxn=1005;
int n,m;
int x1,y1,x2,y2;
int map[maxn][maxn];
struct node
{
int x,y;
int num;
int point;
};
bool flag[maxn][maxn];
int next[4][2]={0,1,0,-1,-1,0,1,0};
node q[1000005];
int top,base;
bool check(int xx1,int yy1)
{
if(map[xx1][yy1]==0&&flag[xx1][yy1]==0&&xx1>0&&xx1<=n&&yy1>0&&yy1<=m)
return 1;
return 0;
}
bool check_ans()
{
int xx1,yy1,xx2,yy2;
xx1=q[base].x;yy1=q[base].y;
for(int i=0;i<4;i++)
{
xx2=xx1+next[i][0];yy2=yy1+next[i][1];
if(xx2<1||xx2>n||yy2<1||yy2>m) continue;
if(xx2==x2&&yy2==y2){
if(q[base].num<2) return 1;
else if(i==q[base].point) return 1;
}
}
return 0;
}
bool bfs()
{
bool ans=false;
while(base<top){
int xx1,yy1,xx2,yy2;
xx1=q[base].x;yy1=q[base].y;
// printf("xx2:%d yy2:%d \n",xx1,yy1);
// if(xx1==x2&&yy1==y2)
//{
if(check_ans()) return 1;
//}
for(int i=0;i<4;i++)
{
xx2=xx1+next[i][0];yy2=yy1+next[i][1];
if(q[base].num<2){
if(check(xx2,yy2))
{
q[top].x=xx2;q[top].y=yy2;
q[top].point=i;
if(q[base].point==-1) q[top].num=0;
else if(q[base].point==q[top].point) q[top].num=q[base].num;
else q[top].num=q[base].num+1;
flag[xx2][yy2]=1;
top++;
}
}
else{
if(i==q[base].point&&check(xx2,yy2)){
q[top].x=xx2;
q[top].y=yy2;
q[top].point=i;
q[top].num=q[base].num;
flag[xx2][yy2]=1;
top++;
}
}
}
base++;
}
return false;
}
int main()
{
while(1){
scanf("%d%d",&n,&m);
if(n==0&&m==0) break;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
scanf("%d",&map[i][j]);
}
int qq;
scanf("%d",&qq);
for(int i=1;i<=qq;i++)
{
memset(q,0,sizeof(q));
memset(flag,0,sizeof(flag));
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if(x1==x2&&y1==y2) {
printf("NO\n");
continue;
}
if(!map[x1][y1]||!map[x2][y2]||map[x1][y1]!=map[x2][y2])
{
printf("NO\n");
continue;
}
top=base=0;
q[top].x=x1;q[top].y=y1;q[top].num=0;q[top++].point=-1;
bool ans=bfs();
if(ans) printf("YES\n");
else printf("NO\n");
}
}
return 0;
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步