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
分析:一开始开队列使用广搜,居然爆时间,切回深搜,关键是遇到“转了两次弯还和终点不在同一行或同一列”这种情况直接剪掉就能ac了。
#include<iostream>
#include<vector>
#include<cstdio>
#include<queue>
#include<string>
#include<algorithm>
#include<cmath>
#include<iomanip>
using namespace std;
const int maxn = 1005;
int matrix[maxn][maxn];
int vis[maxn][maxn];
int n, m, q;
int sx, sy, ex, ey;
int Move[4][2] = { {1,0},{0,1},{-1,0},{0,-1} }; //四个方向移动
int flag; //当有解的时候设为true,一开始设为false
bool bound(int x, int y) //越界判断
{
if (x <= 0 || y <= 0 || x > n || y > m || vis[x][y])
return true;
return false;
}
void dfs(int x,int y,int dir,int turn)
{
if (flag || turn > 2) return;
if (turn == 2 && (x != ex && y != ey)) //转了两次依然没跟终点在同一行,进行剪枝
return;
if (x == ex&&y == ey&&turn <= 2) //符合条件
{
flag = 1;
return;
}
for (int i = 0; i < 4; i++)
{
int tx = x + Move[i][0], ty = y + Move[i][1];
if (bound(tx, ty))
continue;
if (matrix[tx][ty] == 0 || (tx == ex&&ty == ey)) //当该位置为0(即可走)或者已经到达终点,递归进入下一次
{
vis[tx][ty] = 1; //标记已走
if (dir == -1 || dir == i) //如果跟一开始的方向相同或者跟前一次的方向一样,则不转弯
dfs(tx, ty, i, turn);
else
dfs(tx, ty, i, turn + 1);
vis[tx][ty] = 0; //回溯
}
}
return;
}
int main()
{
while (cin >> n >> m)
{
if (n + m == 0)
break;
memset(matrix, 0, sizeof(matrix));
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
cin >> matrix[i][j];
}
cin >> q;
while (q--)
{
cin >> sx >> sy >> ex >> ey;
memset(vis, 0, sizeof(vis));
flag = 0;
if (matrix[sx][sy] == matrix[ex][ey] && matrix[ex][ey])
dfs(sx, sy, -1, 0); //一开始走的方向为-1
if (flag)
cout << "YES" << endl;
else cout << "NO" << endl;
}
}
return 0;
}