连连看

题目
解释

剪枝的搜索,BFS与DFS都可以

代码
//连连看
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<queue>
using namespace std;
struct xjf{
	int x, y, loststop, fan;
}now,well;
int dis[4][2] = { {0,1 }, { 0,-1 }, { 1,0 }, { -1,0 } };
int arr[1005][1005];
int endx,endy,n,m;
int DFS(xjf A) {
	int flag[1005][1005] ;
	memset(flag, 11, sizeof(flag));
	queue <xjf> Q;
	A.fan = 0;
	A.loststop = 0;
	Q.push(A);
	while (!Q.empty()) {
		now = Q.front();
		Q.pop();
		if (now.x == endx && now.y == endy && now.fan < 3) {
			return 1;
		}
		if (now.fan < 3) {
			for (int i = 0; i < 4; i++) {
				int ix = now.x + dis[i][0];
				int iy = now.y + dis[i][1];
				if (ix >= 0 && iy >= 0 && ix < n && iy < m && (arr[ix][iy] == 0 || (ix == endx &&iy == endy))) {
					well.x = ix;
					well.y = iy;
					well.fan = now.fan;
					if (now.loststop == 0) well.loststop = dis[i][0] * 10 + dis[i][1];
					else if (now.loststop == dis[i][0] * 10 + dis[i][1]) {
						well.loststop = dis[i][0] * 10 + dis[i][1];
					}
					else if (now.loststop + dis[i][0] * 10 + dis[i][1]==0) {
						continue;
					}
					else {
						well.loststop = dis[i][0] * 10 + dis[i][1];
						well.fan ++;
					}
					if (flag[ix][iy] > well.fan && well.fan <= 2){
						flag[ix][iy] = well.fan;
						Q.push(well);
					}
				}
			}
		}
	}
	return 0;
}
int main() {
	while (cin >> n >> m) {
		if (n == 0 && m == 0)
			break;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				cin >> arr[i][j];
			}
		}
		int t;
		cin >> t;
		while (t--) {
			xjf A;
			cin >> A.x >> A.y >> endx >> endy;
			endx--;
			endy--;
			A.x--;
			A.y--;
			if ((A.x == endx && A.y == endy)||A.x<0||A.x>=n||A.y<0||A.y>=m || endx < 0 || endx >= n || endy < 0 || endy >= m) {
				cout << "NO" << endl;
				continue;
			}
			if (arr[A.x ][A.y ] == arr[endx ][endy]&& arr[A.x][A.y] != 0) {
				if (DFS(A) == 1) cout << "YES" << endl;
				else cout << "NO" << endl;
			}
			else {
				cout << "NO" << endl;
			}
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值