您的位置:首页 > 其它

HDOJ 1010 Tempter of the Bone

2012-10-15 16:06 323 查看
题意:一个N * M 的迷宫, 起点为S, 终点为D , 障碍为X, 问你是否恰好花费时间T 的时候到达终点D。

思路:DFS ,纯粹的搜索会直接超时, 所以需要通过剪枝, 也是在网上看到别人说奇偶剪枝,加进去直接AC了。

69234052012-10-15 15:09:01Accepted1010640MS256K1465BC++罗维
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
using namespace std;

struct point
{
	int x, y;
};
int n, m, t;
point spt, dpt;
string maze[10];
//vector<vecot<int> >used;
bool escape;

void dfs(point pt, int t)
{
	int tmp = t - abs(pt.x-dpt.x) - abs(pt.y - dpt.y);
	if(pt.x == dpt.x && pt.y == dpt.y && t == 0)
	{
		escape = true;	
		return ;
	}
	//剪枝
	if (escape || tmp < 0 || tmp&1 )  //tmp&1 如果是奇数则为1 否则为0
		return;
	maze[pt.x][pt.y] = 'X';
	if(pt.x + 1 <n && maze[pt.x + 1][pt.y] != 'X')
	{
		pt.x += 1;
		dfs(pt, t-1);
		pt.x -= 1;
		if(escape) return;
	}
	if(pt.x - 1 >=0 && maze[pt.x - 1][pt.y] != 'X')
	{
		pt.x -= 1;
		dfs(pt, t-1);
		pt.x += 1;
		if(escape) return;
	}
	if(pt.y + 1 < m && maze[pt.x][pt.y + 1] != 'X')
	{
		pt.y += 1;
		dfs(pt, t-1);
			pt.y -= 1;
		if(escape) return;
	}
	if(pt.y - 1 >= 0 && maze[pt.x][pt.y - 1] != 'X')
	{
		pt.y -= 1;
		dfs(pt, t-1);
			pt.y += 1;
		if(escape) return;
	}
	maze[pt.x][pt.y] = '.';
}

int main()
{
	int i, j;
	while(cin>>n>>m>>t && n+m+t != 0)
	{
		for (i=0; i<n; i++)
		{
			cin>>maze[i];
			for (j=0; j<m; j++)
			{
				if(maze[i][j] == 'S')
				{
					spt.x = i;
					spt.y = j;
				}
				else if(maze[i][j] == 'D')
				{
					dpt.x = i;
					dpt.y = j;
				}
			}
		}

		escape = false;
		dfs(spt, t);
		if(escape)
			cout<<"YES"<<endl;
		else
			cout<<"NO"<<endl;
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: