hduoj_1010(dfs, 奇偶剪枝)

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char map[7][7];
int v[7][7];

int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };

int n, m, t;

int flag;

int cnt;

int dogX, dogY, doorX, doorY;

// 奇偶剪枝
void dfs(int x, int y, int time)
{
	
	int temp;

	int i;
	if (time > t || 1 == flag) return;
	else if (time == t && map[x][y] == 'D')
	{
		flag = 1;
		return;
	}
	else
	{
		for (i = 0; i < 4; i++)
		{
			if (x + dx[i] > 0 && y + dy[i] > 0 && x + dx[i] <= n&&y + dy[i] <= m && 'X' != map[x+dx[i]][y+dy[i]])
			{
				if (!v[x + dx[i]][y + dy[i]])
				{
					temp = t - time - 1 - abs(x + dx[i] - doorX) - abs(y + dy[i] - doorY);

					if (temp < 0 || 1 == temp % 2) continue;
					v[x + dx[i]][y + dy[i]] = 1;
					dfs(x + dx[i], y + dy[i], time + 1);
					v[x + dx[i]][y + dy[i]] = 0;               // 回溯
				}
				
			}	
		}
	}


}

int main()
{
	int i, j;
	while (EOF != scanf("%d %d %d", &n, &m, &t) && (n || m || t))
	{
		getchar();
		memset(v, 0, sizeof(v));

		for (i = 1; i <= n; i++)
		{
			for (j = 1; j <= m; j++)
			{
				scanf("%c", &map[i][j]);

				if (map[i][j] == 'S')
				{
					dogX = i;
					dogY = j;
					v[i][j] = 1;
				}

				if (map[i][j] == 'D')
				{
					doorX = i;
					doorY = j;
				}
			}
			getchar();
		}

		flag = 0;
		dfs(dogX, dogY, 0);
		if (flag) printf("YES\n");
		else printf("NO\n");
	}
	return 0;
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32862515/article/details/80686990
个人分类: 算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭