码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1010 dfs 走到终点时刚好花掉所有时间 奇偶性剪枝

时间:2015-05-15 21:19:35      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

题意:输入一个n*m的迷宫,和一个T:可以在迷宫中生存的最大时间。S为起点,D为终点。并且,每个格子只能踩一次,且只能维持一秒,然后该块地板就会塌陷。所以你必须每秒走一步,且到D点时,所用时间为T。用深搜。
奇偶性剪枝:如果当前的狗所在的坐标与D的坐标奇偶性不一样,那么狗需要走奇数步。
同理,如果狗所在坐标与D的坐标奇偶性一样,那么狗需要走偶数步数。

也就是说,狗的坐标x、y和对2取余是它的奇偶性,Dxy和对2取余是D的奇偶性。
两个奇偶性一加再对2取余,拿这个余数去与剩下时间对2取余的余数作比较即可。

Sample Input
4 4 5
S.X.
..X.
..XD
....
3 4 5
S.X.
..X.
...D
0 0 0

Sample Output
NO
YES

 

技术分享
 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <iostream>
 4 #include <cmath>
 5 #include <vector>
 6 #include <queue>
 7 
 8 using namespace std;
 9 
10 
11 int m,n,t;
12 char map[8][8];
13 int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
14 int ex,ey,sx,sy,ok;//e表示end,终点,s表示start,出发点,ok用来判断是否在规定时间到达
15 
16 void dfs(int x,int y,int cnt)
17 {
18     int i;
19     if(cnt==t)//剪枝:到时间了符合条件ok=1再退出,不符合条件直接退出。
20     {
21         if(ex==x&&ey==y)ok=1;
22         return;
23     }
24     if(ok)return;//找到解后还有部分在继续搜索,这条是为了让其它搜索停止
25 
26     for(i=0;i<4;i++)
27     {
28         int fx=x+dir[i][0];
29         int fy=y+dir[i][1];
30         if(fx>=0&&fx<n&&fy>=0&&fy<m&&map[fx][fy]!=X)
31         {
32             map[fx][fy]=X;
33             dfs(fx,fy,cnt+1);
34             map[fx][fy]=.; //回溯
35         }
36     }
37 }
38 int main()
39 {
40     int i,j;
41     //freopen("in.txt","r",stdin);
42     while(scanf("%d%d%d",&n,&m,&t))
43     {
44         if (m == 0 && n == 0 & t == 0)
45             break ;
46 
47         for(i=0;i<n;i++)
48         {
49             scanf("%s",map[i]);
50             for(j=0;map[i][j]!=\0;j++)
51             {
52                 if(map[i][j]==S)
53                 {
54                     sx=i;sy=j;
55                 }
56                 else if(map[i][j]==D)
57                 {
58                     ex=i;ey=j;
59                 }
60 
61             }
62         }
63         if(abs(sx - ex) + abs(sy - ey) > t || (sx +sy+ex+ey+t)%2 == 1)//如果步数大于时间 或步数的奇偶性不一致
64             printf("NO\n");
65         else
66         {
67             ok=0;
68             map[sx][sy]=X;
69             dfs(sx,sy,0);
70             if(ok)printf("YES\n");
71             else printf("NO\n");
72         }
73     }
74     return 0;
75 }
View Code

 

hdu 1010 dfs 走到终点时刚好花掉所有时间 奇偶性剪枝

标签:

原文地址:http://www.cnblogs.com/-Buff-/p/4506784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!