杭电OJ 1010

杭电OJ 1010_第1张图片

奇偶剪枝:http://baike.baidu.com/view/7789287.htm 百度百科,假设起点是sx,sy终点是ex,ey那么abs(ex-sx)+abs(ey-ey)为起点到终点的最短步数。起点到终点的步数要么是最短步数(最短步数+0),要么是最短步数+一个偶数(偏移路径)

#include
#include   
#include
#include  
using namespace std;
int dir[4][2] = { 1, 0, -1, 0, 0, -1, 0, 1 };
bool flag;
bool vis[10][10];
int xs, ys, xd, yd;
int n, m, t;
char map[8][8];
int ABS(int a)
{
	if (a < 0)
		return -a;
	else
		return a;
}

void dfs(int x, int y, int time)
{
	if (x < 0 || y < 0 || x >= n || y >= m)
		return;
	if (map[x][y] == 'X')
		return;
	if (vis[x][y] == 1)
		return;
	vis[x][y] = 1;
	if (x == xd&&y == yd&&time == t)
	{
		flag = true;
		return;
	}
	if (time == t && (x != xd || y != yd))
		return;
	if (time > t)
		return;
	for (int i = 0; i < 4; i++)
	{
		int xt = x + dir[i][0];
		int yt = y + dir[i][1];
		if (xt < 0 || xt >= n || yt < 0 || yt >= m || map[xt][yt] == 'X' || vis[xt][yt] == 1)
			continue;
		dfs(xt, yt, ++time);
		vis[xt][yt] = 0;
		time--;
		if (flag == 1)
			return;
	}
}

int main()
{


	while (cin >> n >> m >> t && n && m && t)
	{
		map[n][m];
		for (int i = 0; i < n; ++i)
		{
			cin >> map[i];
			for (int j = 0; j < m; ++j)
			{
				if (map[i][j] == 'S')
				{
					xs = i;
					ys = j;
				}
				if (map[i][j] == 'D')
				{
					xd = i;
					yd = j;
				}
			}

		}
		int ms = ABS(xd - xs) + ABS(yd - ys);
		if (t < ms)
		{
			cout << "NO\n";
			continue;
		}
		if ((t - ms) % 2)
		{
			cout << "NO\n";
			continue;
		}
		flag = false;
		memset(vis, 0, sizeof(vis));
		dfs(xs, ys, 0);
		if (flag)
			cout << "Yes\n";
		else
			cout << "NO\n";
	}
	return 0;
}

你可能感兴趣的:(杭电OJ)