hdu 1175 连连看 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1175
BFS水
题目大意:不能从外围通过的,转向限制为2的连连看,BFS就好了。
题目分析:二维数组存图,另有visit数组并每次查询前初始化,控turn也很重要。
code:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define N 1050
short int map[N][N],m,n,vis[N][N];
int dir[4][2]={1,0,-1,0,0,1,0,-1},ex,ey;
struct node
{
int x,y,turn;
};
bool judge(int x,int y)
{
return x>=0&&y>=0&&x<m&&y<n&&map[x][y]==0;
}
bool bfs(int x,int y)
{
queue<node>que;
node first,next;
first.x=x,first.y=y,first.turn=-1;
que.push(first);
while(!que.empty())
{
first=que.front();
que.pop();
for(int i=0;i<4;i++)
{
next.x=first.x+dir[i][0];
next.y=first.y+dir[i][1];
if(next.x==ex&&next.y==ey)return true;
while(judge(next.x,next.y))
{
next.turn=first.turn+1;
if(vis[next.x][next.y]==0&&next.turn<2)
{//这里注意,必须是还能再转一次的才有资格进
que.push(next);
vis[next.x][next.y]=1;
}
next.x+=dir[i][0];
next.y+=dir[i][1];
if(next.x==ex&&next.y==ey)return true;
}
}
}
return false;
}
int main()
{
int i,j,sx,sy,query;
while(cin>>m>>n&&m|n)
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>map[i][j];
}
}
cin>>query;
while(query--)
{
memset(vis,0,sizeof(vis));
cin>>sx>>sy>>ex>>ey;
sx--,sy--,ex--,ey--;
if(map[sx][sy]==0||map[ex][ey]==0)printf("NO\n");
else if(map[sx][sy]!=map[ex][ey])printf("NO\n");
else printf("%s\n",bfs(sx,sy)?"YES":"NO");
}
}
return 0;
}
Exe.Time Exe.Memory Code Len.
2781MS 8288K 1366 B