类型:搜索[DFS]
题目:给定迷宫,判断是否能够刚好用T步到达目标格点
来源:Zhejiang Provincial Programming Contest 2004
思路:dfs + 剪枝,当达到目标时,做标记并退出,当未达到目标且当前位置为门时退出
// ZOJ 2110 Tempter of the Bone
// tle ac 1550ms 188kb
#include <iostream>
#include <sstream>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include <map>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <set>
#include <deque>
#include <bitset>
#include <functional>
#include <utility>
#include <iomanip>
#include <cctype>
using namespace std;
#define FOR(i,a,b) for(i = (a); i < (b); ++i)
#define FORE(i,a,b) for(i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(i = (a); i > (b); --i)
#define FORDE(i,a,b) for(i = (a); i >= (b); --i)
#define max(a,b) ((a) > (b)) ? (a) : (b)
#define min(a,b) ((a) < (b)) ? (a) : (b)
#define CLR(a,b) memset(a,b,sizeof(a))
#define PB(x) push_back(x)
const int MAXN = 10000;
const int MAXM = 0;
const int hash_size = 25000002;
const int INF = 0x7f7f7f7f;
map<string, int> mp;
map<string, int>::iterator it;
int N, M, T;
int ex, ey, sx, sy;
int px[4] = {-1, 0, 1, 0}, py[4] = {0, 1, 0, -1};
bool sign;
bool vis[10][10];
char m[10][10];
void dfs(int step, int x, int y) {
int tx, ty, i;
if(sign)
return ;
if(step == T) {
if(x == ex && y == ey)
sign = true;
return ;
}
//!!!
if(x == ex && y == ey)
return ;
FOR(i, 0, 4) {
tx = x + px[i], ty = y + py[i];
if(tx < 0 || tx >= N || ty < 0 || ty >= M || vis[tx][ty] || m[tx][ty] == 'X')
continue;
vis[tx][ty] = true;
dfs(step + 1, tx, ty);
//!!!
if(sign)
return ;
vis[tx][ty] = false;
}
}
int main() {
int i, j;
while(scanf("%d %d %d", &N, &M, &T) == 3, N || M || T) {
FOR(i, 0, N) {
scanf("%s", m[i]);
FOR(j, 0, M) {
if(m[i][j] == 'S')
sx = i, sy = j;
if(m[i][j] == 'D')
ex = i, ey = j;
}
}
sign = false;
CLR(vis, false);
vis[sx][sy] = true;
dfs(0, sx, sy);
if(sign)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}