这道题考查了深搜和剪枝,首先要恰好在t的时间内到达,从起点(bx, by)到终点(ex, ey)的最短距离为abs(ex-bx)+abs(ey-by),如果t小于最小距离就是NO。
另外t与最短距离之差如果是奇数也一定是NO。
#include <cstdio>
#include <cstring>
#include <cstdlib>
char maze[8][8];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
bool vis[8][8];
int n, m, t;
bool flag;
void Dfs(int x, int y, int tm) {
// printf("%d %d\n", x, y);
if (flag) {
return;
}
if (maze[x][y] == 'D' || tm == t) {
if (maze[x][y] == 'D' && tm == t) {
flag = true;
}
return;
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m
&& vis[nx][ny] == false && maze[nx][ny] != 'X') {
vis[nx][ny] = true;
Dfs(nx, ny, tm + 1);
vis[nx][ny] = false;
}
}
}
int main(int argc, char const *argv[]) {
while (scanf("%d%d%d", &n, &m, &t) == 3 && n + m + t) {
getchar();
int bx, by;
int ex, ey;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%c", &maze[i][j]);
if (maze[i][j] == 'S') {
bx = i;
by = j;
}
if (maze[i][j] == 'D') {
ex = i;
ey = j;
}
}
getchar();
}
if (abs(ex-bx) + abs(ey-by) > t || (t - (abs(ex-bx) + abs(ey-by))) % 2 == 1) {
puts("NO");
continue;
}
memset(vis, false, sizeof(vis));
flag = false;
vis[bx][by] = true;
Dfs(bx, by, 0);
puts(flag ? "YES" : "NO");
}
return 0;
}