1. 程式人生 > >hdoj 1010-Tempter of the Bone

hdoj 1010-Tempter of the Bone

nta put com problem pty less 清空 beginning art

Problem Description The doggie found a bone in an ancient maze, which fascinated him a lot. However, when he picked it up, the maze began to shake, and the doggie could feel the ground sinking. He realized that the bone was a trap, and he tried desperately to get out of this maze.

The maze was a rectangle with sizes N by M. There was a door in the maze. At the beginning, the door was closed and it would open at the T-th second for a short period of time (less than 1 second). Therefore the doggie had to arrive at the door on exactly the T-th second. In every second, he could move one block to one of the upper, lower, left and right neighboring blocks. Once he entered a block, the ground of this block would start to sink and disappear in the next second. He could not stay at one block for more than one second, nor could he move into a visited block. Can the poor doggie survive? Please help him. Input The input consists of multiple test cases. The first line of each test case contains three integers N, M, and T (1 < N, M < 7; 0 < T < 50), which denote the sizes of the maze and the time at which the door will open, respectively. The next N lines give the maze layout, with each line containing M characters. A character is one of the following:

‘X‘: a block of wall, which the doggie cannot enter;
‘S‘: the start point of the doggie;
‘D‘: the Door; or
‘.‘: an empty block.

The input is terminated with three 0‘s. This test case is not to be processed. Output For each test case, print in one line "YES" if the doggie can survive, or "NO" otherwise. Sample Input 4 4 5 S.X. ..X. ..XD .... 3 4 5 S.X. ..X. ...D 0 0 0 Sample Output NO YES 題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1010 用深度搜索和奇偶剪枝即可解決 奇偶剪枝-百度百科(裏面原理補充部分講的很好理解):https://baike.baidu.com/item/%E5%A5%87%E5%81%B6%E5%89%AA%E6%9E%9D/10385689
#include <iostream>
#include 
<cstring> #include <cstdio> using namespace::std; int N,M,T,t; char maps[10][10]; int maps_[10][10]; int stx,sty,enx,eny; int a[4][2] = {{1,0},{-1,0},{0,1},{0,-1}}; bool dfs(int n,int m) { if( n == enx && m == eny && t == T ) { return true; }
int ans = T-t-abs(enx-n)-abs(eny-m); //奇偶剪枝,感覺好吊。 if(ans<0 || ans&1) return false; for(int i = 0;i<4;i++) { int x = n + a[i][0]; int y = m + a[i][1]; if(maps[x][y] != X && maps_[x][y] != 1 && x>=0 && y>= 0 && x<N && y<M) { t++; maps_[x][y] = 1; if(dfs(x,y)) return true; else{ t--; maps_[x][y] = 0; } } } return false; } int main() { while(scanf("%d %d %d",&N,&M,&T) && N != 0) { memset(maps,0,sizeof(maps)); //每次輸入把地圖和標記清空 memset(maps_,0,sizeof(maps_)); for(int i=0; i<N; i++) { scanf("%s",&maps[i]); for(int j = 0; j<M;j++) { if(maps[i][j] == S) //起始點 { stx = i; sty = j; } else if(maps[i][j] == D) //終點 { enx = i; eny = j; } } } t = 0; maps_[stx][sty] = 1; //標記起點 if(dfs(stx,sty)) { printf("YES\n"); }else printf("NO\n"); } return 0; }

hdoj 1010-Tempter of the Bone