【HDOJ】1010 Tempter of the Bone
经典搜索+剪枝,这还是第一次知道什么是剪枝,主要还是奇偶剪枝,这题非常经典。
#include <iostream> #include <cstdio> using namespace std; #define MAXNUM 10 int n, m, t; char maze[MAXNUM][MAXNUM]; // upper, lower, left and right int direction[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int si, sj, di, dj; bool survive; void dfs(int si, int sj, int cnt) { int tmp1, tmp2; if (cnt==t && si==di && sj==dj) { survive = true; return ; } tmp1 = abs(si-di)+abs(sj-dj); if ( t-cnt < tmp1 ) return ; if ( (t-cnt-tmp1)%2 != 0) return ; for (int i=0; i<4; ++i) { tmp1 = si + direction[i][0]; tmp2 = sj + direction[i][1]; if (tmp1 && tmp2 && tmp1<=n && tmp2<=m && maze[tmp1][tmp2] != 'X') { maze[tmp1][tmp2] = 'X'; dfs(tmp1, tmp2, cnt+1); if ( survive ) return ; maze[tmp1][tmp2] = '.'; } } } int main() { int i, j; int wall; while (cin>>n>>m>>t) { if (n==0 && m==0 && t==0) break; wall = 0; for (i=1; i<=n; ++i) { for (j=1; j<=m; ++j) { cin >>maze[i][j]; if (maze[i][j] == 'S') { si = i; sj = j; } if (maze[i][j] == 'D') { di = i; dj = j; } if (maze[i][j] == 'X') wall++; } } if (n*m-wall < t) { printf("NO\n"); } else { survive = false; maze[si][sj] = 'X'; dfs(si, sj, 0); if (survive) printf("YES\n"); else printf("NO\n"); } } return 0; }