HDOJ 1010 Tempter of the Bone
先上贴老掉牙深度优先版本的,算是第一次使用搜索,伤透了哥的❤。其实刚开始一直尝试在用广度优先做,一直WA。后来认真思考一下将状态同数据一起存储,怎奈仍然无法通过。期待与有广度优先的筒子一起探讨,持续努力中……

1 //#include <fstream>
2 #include <iostream>
3 #include <string>
4
5 using namespace std;
6 char maze[8][8];
7 int n,m,t,di,dj;
8 bool escape;
9 int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}};
10 void dfs(int si,int sj,int cnt)
11 {
12 int i,temp;
13 if(cnt==t&&si==di&&sj==dj) escape=1;
14 if(si>n||sj>m||si<=0||sj<=0||escape) return;
15
16 temp=(t-cnt)-abs(si-di)-abs(sj-dj);
17 if(temp<0||temp&1) return;//步长优化与奇偶优化
18 for(i=0;i<4;i++){
19 if(maze[si+dir[i][0]][sj+dir[i][1]]!='X')
20 {
21 maze[si+dir[i][0]][sj+dir[i][1]]='X';
22 dfs(si+dir[i][0],sj+dir[i][1],cnt+1);
23 maze[si+dir[i][0]][sj+dir[i][1]]='.'; //回退的说
24 }
25 }
26 return;
27 }
28 int main()
29 {
30 //ifstream cin("Tempter of the Bone.txt");
31 int i,j,si,sj;
32 while(cin>>n>>m>>t)
33 {
34 if(n==0&&m==0&&t==0) break;
35 int wall=0;
36 for(i=1;i<=n;i++)
37 for(j=1;j<=m;j++)
38 {
39 cin>>maze[i][j];
40 if(maze[i][j]=='S') { si=i; sj=j; }
41 else if(maze[i][j]=='D') { di=i; dj=j; }
42 else if(maze[i][j]=='X') wall++;
43 }
44 if(n*m-wall<=t)
45 {
46 cout<<"NO"<<endl;
47 continue;
48 }
49 escape=0;
50 maze[si][sj]='X';
51 dfs(si,sj,0);
52 if(escape)
53 cout<<"YES"<<endl;
54 else
55 cout<<"NO"<<endl;
56 }
57 return 0;
58 }