http://acm.hdu.edu.cn/showproblem.php?pid=1010
DFS
我的代码
1 #include <stdio.h>
2 #include <stdlib.h>
3 const int dx[]={0,1,0,-1};
4 const int dy[]={1,0,-1,0};
5 int n,m,t,sx,sy,ex,ey,ans;
6 char maze[10][10];
7 void dfs(int x,int y,int s)
8 {
9 if (ans) return;
10 if (abs(ex-x)+abs(ey-y)+s>t) return;
11 int i,nx,ny;
12 for (i=0;i<4;i++)
13 {
14 nx=x+dx[i]; ny=y+dy[i];
15 if (nx==ex && ny==ey && s+1==t) {ans=1; return;}
16 if (0<=nx && nx<n && 0<=ny && ny<m && maze[nx][ny]=='.')
17 {
18 maze[nx][ny]='X';
19 dfs(nx,ny,s+1);
20 maze[nx][ny]='.';
21 }
22 }
23 }
24 int main()
25 {
26 int i,j;
27 while (scanf("%d%d%d",&n,&m,&t) && (n||m||t))
28 {
29 ans=0;
30 for (i=0;i<n;i++) scanf("%s",maze[i]);
31 for (i=0;i<n;i++)
32 for (j=0;j<m;j++)
33 {
34 if (maze[i][j]=='S') {sx=i; sy=j;}
35 if (maze[i][j]=='D') {ex=i; ey=j;}
36 }
37 if ((sx+sy+t)%2!=(ex+ey)%2) {printf("NO\n"); continue;}
38 maze[sx][sy]='X';
39 dfs(sx,sy,0);
40 if (ans) printf("YES\n");
41 else printf("NO\n");
42 }
43 }