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