HDU 1175 (DFS+剪枝)

很有意思的一题哈……

(写完了把每次错的就改正了重新提交我可去你的吧=A=)

看完题目硬是想不出怎么判断转了一个弯 紫书上也有转弯的题但是感觉和这个不一样……

剪枝和象棋那个题有点像很好理解

烦的是莫名其妙的WA(死在粗心打错看不到)

内容很简单很普通的DFS……细心点做……

#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <cmath>
using namespace std;

int n, m;
int mm[1005][1005];
int vis[1005][1005];
int mov[][2] = { 0,1,1,0,0,-1,-1,0 };
int flag;

bool judge(int x, int y)
{
	if (x<1 || x>n || y<1 || y>m)
		return false;
	return true;
}

void dfs(int x1, int y1, int x2, int y2, int dir, int turn)
{
	if (flag || turn > 2)return;
	if (turn == 2 && x1 != x2 && y1 != y2)return;
	for (int i = 0; i < 4; i++)
	{
		int xx = x1 + mov[i][0];
		int yy = y1 + mov[i][1];
		if (xx == x2 && yy == y2)
		{
			flag = 1;
			return;
		}
		if (!judge(xx, yy) || mm[xx][yy] != 0 || vis[xx][yy] == 1)continue;
		vis[xx][yy] = 1;
		if (i == dir || dir == -1)
			dfs(xx, yy, x2, y2, i, turn);
		else
			dfs(xx, yy, x2, y2, i, turn + 1);
		vis[xx][yy] = 0;
	}
}

int main()
{

	while (cin >> n >> m && n != 0 && m != 0)
	{
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= m; j++)
				cin >> mm[i][j];

		int q;
		cin >> q;
		while (q--)
		{
			memset(vis, 0, sizeof(vis));
			flag = 0;
			int x1, y1, x2, y2;
			cin >> x1 >> y1 >> x2 >> y2;
			if (mm[x1][y1] != mm[x2][y2] || mm[x1][y1] == 0 || (x1 == x2 && y1 == y2) || !judge(x1, y1) || !judge(x2, y2))
			{
				cout << "NO" << endl;
				continue;
			}

			dfs(x1, y1, x2, y2, -1, 0);
			if (flag)
				cout << "YES" << endl;
			else
				cout << "NO" << endl;
		}
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42191950/article/details/82957792