传送门 : http://acm.hdu.edu.cn/showproblem.php?pid=1175
连连看
Time Limit: 20000/10000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 39790 Accepted Submission(s): 9844
Problem Description
“连连看”相信很多人都玩过。没玩过也没关系,下面我给大家介绍一下游戏规则:在一个棋盘中,放了很多的棋子。如果某两个相同的棋子,可以通过一条线连起来(这条线不能经过其它棋子),而且线的转折次数不超过两次,那么这两个棋子就可以在棋盘上消去。不好意思,由于我以前没有玩过连连看,咨询了同学的意见,连线不能从外面绕过去的,但事实上这是错的。现在已经酿成大祸,就只能将错就错了,连线不能从外围绕过。
玩家鼠标先后点击两块棋子,试图将他们消去,然后游戏的后台判断这两个方格能不能消去。现在你的任务就是写这个后台程序。
Input
输入数据有多组。每组数据的第一行有两个正整数n,m(0 < n<= 1000,0 < m<1000),分别表示棋盘的行数与列数。在接下来的n行中,每行有m个非负整数描述棋盘的方格分布。0表示这个位置没有棋子,正整数表示棋子的类型。接下来的一行是一个正整数q(0< q<50),表示下面有q次询问。在接下来的q行里,每行有四个正整数x1,y1,x2,y2,表示询问第x1行y1列的棋子与第x2行y2列的棋子能不能消去。n=0,m=0时,输入结束。
注意:询问之间无先后关系,都是针对当前状态的!
Output
每一组输入数据对应一行输出。如果能消去则输出”YES”,不能则输出”NO”。
Sample Input
3 4
1 2 3 4
0 0 0 0
4 3 2 1
4
1 1 3 4
1 1 2 4
1 1 3 3
2 1 2 4
3 4
0 1 4 3
0 2 4 1
0 0 0 0
2
1 1 2 4
1 3 2 3
0 0
Sample Output
YES
NO
NO
NO
NO
YES
写这道题 一直T ,改了好久好久才ac
解释都在代码中 就不说了
#include <iostream>
#include <string.h>
#include <algorithm>
//#include <bits/stdc++.h>
#include <queue>
#include <cstdio>
using namespace std;
int Map[1003][1003]; //存储坐标信息
int vist[1003][1003]; //存储该坐标下最少的转弯数
int cx[4][2] = {0,1,0,-1,1,0,-1,0}; //4个方向
int xx1,xx2,yy1,yy2; //(xx1, yy1)起点, (xx2, yy2)终点
int m,n;
int flag; //标记能否走到 0代表可以, 1代表不可以
struct node
{
int x,y;
int step; //记录当前点转弯数
int dir; //记录当前方向
}now;
void bfs()
{
//memset(sum,111,sizeof(sum));
node next;
queue<node>q;
q.push(now);
while (!q.empty())
{
now = q.front();
q.pop();
if (now.x==xx2&&now.y==yy2) //到达终点
{
flag=0;
//cout<<now.step<<endl;
//cout<<"~~~"<<endl;
return;
}
for (int i=0; i<4; i++) //4个方向
{
next.x = now.x+cx[i][0];
next.y = now.y+cx[i][1];
next.step = now.step;
next.dir = i;
if (now.dir!=-1) //当不在起始位置
{
if (next.dir!=now.dir) //当前位置的方向和上个位置的方向不一样(需要转弯)
{
next.step++;
}
}
if (next.x>=1&&next.x<=m&&next.y>=1&&next.y<=n&&next.step<=2) //不出边界且转弯次数不大于2
{
if (Map[next.x][next.y]==0||(next.x==xx2&&next.y==yy2)) //没有走过(0) 或 到达终点
{
//cout<<"!!!"<<endl;
if (next.step<vist[next.x][next.y]) //判断是否为改点最少转弯数
{
vist[next.x][next.y] = next.step;
q.push(next);
}
}
}
}
}
flag=1;
}
int main()
{
while (scanf("%d%d",&m,&n),m!=0&&n!=0)
{
for (int i=1; i<=m; i++)
{
for (int j=1; j<=n; j++)
{
scanf("%d",&Map[i][j]);
}
}
int num;
scanf("%d",&num);
for (int i=0; i<num; i++)
{
for (int j=1; j<=m; j++)
{
for (int k=1; k<=n; k++)
{
vist[j][k] = 99999999; //初始值用0x3f3f3f或一个比较大的值
}
}
scanf("%d%d%d%d",&xx1,&yy1,&xx2,&yy2);
flag=1;
//起点位置信息,默认开始方向为-1
now.x = xx1;
now.y = yy1;
now.step=0;
now.dir=-1;
if (!Map[xx1][yy1]||!Map[xx2][yy2]||Map[xx1][yy1]!=Map[xx2][yy2]||(xx1==xx2&&yy1==yy2)) //不满足条件
flag=1;
else
bfs();
if (flag==1)
{
printf ("NO\n");
}
else
{
printf ("YES\n");
}
}
}
return 0;
}