HDOJ 1010
#include <cstdio>
#include <cmath>
using namespace std;
int n, m, t, sx, sy, ex, ey;
char maze[8][8];
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
bool escape = false;
int least_distance(int x, int y)
{
return abs(x - ex) + abs(y - ey);
}
void DFS(int x, int y, int step)
{
if (x < 1 || y < 1 || x > n || y > m)
return;
if (x==ex && y==ey && step==t)
{
escape = true;
}
if (escape)
return;
int temp = (t - step) - least_distance(x, y);
if (temp < 0 || temp % 2 == 1)
return;
for (int i = 0; i < 4; ++i)
{
int xt = x + dir[i][0];
int yt = y + dir[i][1];
if (maze[xt][yt] != 'X')
{
maze[xt][yt] = 'X';
DFS(xt, yt, step + 1);
maze[xt][yt] = '.';
}
}
}
int main()
{
// freopen("in.txt", "r", stdin);
while(scanf("%d %d %d", &n, &m, &t) && (n + m + t))
{
getchar();
//printf("%d %d %d\n", n, m, t);
escape = false;
int wall = 0;
sx = sy = ex = ey = 0;
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= m; ++j)
{
scanf("%c", &maze[i][j]);
//printf("%c", maze[i][j]);
if(maze[i][j] == 'S')
{
sx = i;
sy = j;
}
if(maze[i][j] == 'D')
{
ex = i;
ey = j;
}
if(maze[i][j] == 'X')
{
wall++;
}
}
getchar();
// printf("\n");
}
if(m * n - wall <= t)
{
printf("NO\n");
continue;
}
maze[sx][sy] = 'X';
DFS(sx, sy, 0);
if(escape)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}