HDU1010_半成品

http://acm.hdu.edu.cn/showproblem.php?pid=1010

题意: n*m迷宫中 S为起点 D为终点 X为墙 , t为时间。 要求: 每一步只能走一次, 走一步消耗一秒, 在消耗的时间刚好为t的时候到达D则小狗生还否则,死亡。(有刚好本题就为DFS题目了, 一开始没注意 做成BFS了)。

注: 用DFS超时了, 需要做剪枝。(下面的代码超时了)

http://blog.csdn.net/liwen_7/article/details/7463596(这个是成品)

#include <cstdio>
#include <stack>
#include <cmath>
using namespace std;

#define	MAX_N 8

struct Node {
	int x, y;
	int time;
	char map[MAX_N][MAX_N];
};

const int direction[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};
int n, m;
char map[MAX_N][MAX_N];
Node end;

bool DFS(Node );
bool ok(Node );

int main()
{
	int t;
	Node star;

	while (scanf("%d%d%d%*c", &n,  &m, &t) && (n || m || t)) {
		//输入地图,同时找出S 和 D 的坐标
		for (int i  = 0; i < n; i++) {
			for (int j = 0; j < m; j++) { 
				scanf("%c", &star.map[i][j]);
				if (star.map[i][j] == 'S') {
					star.x = i; 	
					star.y = j;
					star.time = t;
				}else if (star.map[i][j] == 'D') {
					end.x = i;
					end.y = j;
				}
			}
			getchar();				//回车符
		}

		if (DFS(star)) {
			printf("YES\n");		
		}else {
			printf("NO\n");
		}
	}

	return 0;
}

/********************************************
 * DFS()
 * *****************************************/
bool DFS(Node star) 
{
	stack<Node> sta;
	sta.push(star);

	while (!sta.empty()) {
		Node root = sta.top();
		sta.pop();

		if (root.x == end.x && root.y == end.y && root.time == 0) {
			return true;
		}

		for (int i = 0; i < 4; i++) {
			Node child = root;
			child.x += direction[i][0];
			child.y += direction[i][1];
			child.time--;

			if (ok(child)) {
				child.map[child.x][child.y] = 'X';
				sta.push(child);
			}
		}
	}

	return false;

}

/*******************************************
 * ok
 * ****************************************/
bool ok(Node cur)
{
	if (cur.x >= 0 && cur.x < n && cur.y >= 0 && cur.y < m && cur.time >= 0) {
		if (cur.map[cur.x][cur.y] != 'X') {
			int distance = abs(cur.x - end.x) + abs(cur.y - end.y);
			if (distance <= cur.time) {
				return true;
			}
		}
	}

	return false;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值