【HDUOJ]1010-Tempter of bone DFS+剪枝

xiaoxiao2021-02-28  112

点击打开链接

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

题意:先输入三个数N,M,T,分别表示行列,和要走的步数。s为起始点,D为终点,doggie必须要走T步如果走不到就输出NO否则YES.此题要用到剪枝。

我在这个题这没有想到剪枝,也没想到怎样表示走了多少步,看了学长的之后才恍然大悟。

AC代码:

#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int n,m,c,t; char s[100][100]; int vis[100][100]; int fx[4]={0,0,1,-1},fy[4]={1,-1,0,0}; int ans; void dfs(int x,int y,int nl) { if(c) return; vis[x][y]=1; for(int i=0;i<4;i++) { int xx=x+fx[i]; int yy=y+fy[i]; if(xx>=0&&yy>=0&&xx<n&&yy<m&&!vis[xx][yy]) { if(s[xx][yy]=='.')       dfs(xx,yy,nl+1);      else if(s[xx][yy]=='D'&&nl+1==t)                {     c=1; }    } } vis[x][y]=0;//经过深搜之后要是发现不能走到,就把上一个改为0,防止下一次搜索搜到他不能用,有可能就会WA;  } int main() { while(~scanf("%d%d%d",&n,&m,&t),n) { memset(vis,0,sizeof(vis)); int q,p,g,h; c=0; for(int i=0;i<n;i++) scanf("%s",s[i]); for(int i=0;i<n;i++) for(int j=0;j<m;j++) {  if(s[i][j]=='S')   {  q=i;      p=j;   }   if(s[i][j]=='D')   {   g=i;   h=j;   }     }     if((abs(q-g)+abs(p-h)-t)&1)//剪枝 唯一需要注意是奇偶减枝, //简单来说如果 abs(sx - ex) + abs(sy - ey) 和 步数 T 必须同奇同偶才可以到达     {            printf("NO\n");            continue;          }      dfs(q,p,0);  if(c) printf("YES\n");  else printf("NO\n"); } return 0; }

转载请注明原文地址: https://www.6miu.com/read-21987.html

最新回复(0)