一 题目描述
n m t
4 4 5
S.X.
.
.X.
..
XD
....
在n×m的矩阵中,从‘S’走到‘D’位置,问你用t步能不能走到?典型的搜索题目
二 思路
从起点
‘S’开始,遇到
‘.’就递归搜索,直到到达’D‘,如果恰好走了t步那么递归结束。
剪枝:
- 搜索过程中,如果已经走了大于t步的话,退出
- 起点和终点位置abs(ex-sx) + abs(ey-sy)决定起点到终点步数的奇偶,那么递归时,dfs(int x, int y, int c),C为已走步数,x,y为当前位置,t为总步数,那么(t - c)为待走步数,它跟(abs(ex-sx) + abs(ey-sy))的奇偶性应相同
三 代码
#include <stdio.h>
#include <stdlib.h>
char map[7][7];
int t;
int n,m;
int sx,sy,ex,ey;
int f[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int flag = 0;
void dfs(int x, int y, int c)
{
//printf("%d %d\n", x, y);
if (flag || c > t)
return;
if ( ( t - c - abs(ex-x) - abs(ey-y) ) % 2 != 0)
return;
if (x == ex && y == ey && c == t)
{
flag = 1;
return;
}
int tx,ty;
int i;
for (i = 0; i < 4; ++i)
{
tx = x + f[i][0];
ty = y + f[i][1];
if (tx < 0 || tx >= n || ty < 0 || ty >= m)
continue;
if (map[tx][ty] == '.')
{
map[tx][ty] = 'X';
dfs(tx, ty, c+1);
map[tx][ty] = '.';
}
if (map[tx][ty] == 'D')
dfs(tx, ty, c+1);
}
}
int main()
{
freopen("in.txt", "r", stdin);
while (scanf("%d%d%d", &n, &m, &t) && n)
{
flag = 0;
getchar();
int i,j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < m; ++j)
{
map[i][j] = getchar();
if (map[i][j] == 'S')
sx = i, sy = j;
if (map[i][j] == 'D')
ex = i, ey = j;
}
getchar();
}
dfs(sx, sy, 0);
if (flag)
printf("YES\n");
else
printf("NO\n");
}
}