zoukankan      html  css  js  c++  java
  • hdu 1010 走到终点时刚好花掉所有时间 (DFS + 奇偶性剪枝 )

    题意:输入一个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]!='';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
    ");
    65         else
    66         {
    67             ok=0;
    68             map[sx][sy]='X';
    69             dfs(sx,sy,0);
    70             if(ok)printf("YES
    ");
    71             else printf("NO
    ");
    72         }
    73     }
    74     return 0;
    75 }
    View Code
  • 相关阅读:
    插入排序的Python代码实现
    数据结构基础--二叉堆、优先队列
    数据结构基础--二叉树
    数据结构基础--数组、链表、栈、队列、哈希表
    转:数据结构与算法系列--十大排序(附动态图解
    快速排序的Python代码实现
    选择排序的Python代码实现
    csv文件的读取写法 from Udacity
    Linux下测试ZLAN 5800
    冒泡排序的Python代码实现
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/4506784.html
Copyright © 2011-2022 走看看