hduoj_1010(dfs, 奇偶剪枝)

#include 
#include 
#include 

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;
}

你可能感兴趣的:(算法)