题目
连连看
Time Limit: 20000/10000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 43134 Accepted Submission(s): 10739
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
解题思路
一开始感觉可以用bfs做,但是看见网上很多都是用dfs的加还是那个dfs不是太熟悉就用dfs写了一下,需要剪枝,不然容易超时,详细过程可以看注释
代码
//
// main.cpp
// hdu 1175 dfs
//
// Created by zhan_even on 2018/12/3.
// Copyright © 2018年 zhan_even. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <math.h>
#define M 1005
using namespace std;
int map[M][M];
int dir[4][2] = {{0,1}, {1,0}, {-1,0}, {0, -1}};
bool vis[M][M];
int n, m, x1, x2, ya ,y2;
int flag;
bool check(int x1, int y1, int x2, int y2){
if(x1 < 1 || y1 < 1 || x1 > n || y1 > m || x2 < 1 || y2 < 1 || x2 > n || y2 > m)
return false;
return true;
}
void dfs(int x, int y, int turn, int dirction){
if (flag)
return ;
//走过 或者 点出界
if (x > n || x < 1 || y < 1 || y > m || vis[x][y])
return ;
//剪枝,连连看的要求,转了两次方向之后就不能转了,如果和目标点在一条直线上的话可以到达,在不同直线上的话就不能到达返回
if(turn == 2 && x != x2 && y != y2)
return ;
if(turn > 2)
return ;
//到达终点
if (x == x2 && y == y2 && turn <=2) {
flag = 1;
cout<< "YES" <<endl;
return ;
}
//当前位置不为0, 且不是起点 返回
if (map[x][y] != 0) {
if(x == x1 && y == ya) ;
else
return ;
}
vis[x][y] = 1;
int dx, dy, i;
for (i = 0; i < 4; i++) {
dx = x + dir[i][0];
dy = y + dir[i][1];
//当方向相同的时候转向就不变
if (i == dirction)
dfs(dx, dy, turn, dirction);
//方向不同,turn+1,并且方向改改变
else
dfs(dx,dy,turn+1,i);
}
vis[x][y]=0;//清除标记
return;
}
int main(int argc, const char * argv[]) {
int q;
while (cin >> n >> m && (n || m)) {
memset(vis,0,sizeof(vis));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> map[i][j];
}
}
cin >> q;
while (q--) {
cin >> x1 >> ya >> x2 >> y2;
//如果输入在界外
if (!check(x1, ya, x2, y2)){
cout << "NO" <<endl;
continue;
}
//如果起点与终点相同则无法消除
if (x1 == x2 && ya ==y2 ) {
cout << "NO" <<endl;
continue;
}
//起点终点位置行灯并且不是0时才能进行查找
if(map[x1][ya] == map[x2][y2] && map[x1][ya]){
flag = 0;
//从一个点的四个方向开始进行查找
for(int i = 0; i < 4; i++)
dfs(x1, ya, 0, i);
if(!flag)
cout << "NO" <<endl;
}
else
cout << "NO" << endl;
}
}
return 0;
}