zoukankan      html  css  js  c++  java
  • 【DFS】POJ3009-Curling 2.0

    【题目大意】

    给出一张地图,一旦往一个方向前进就必须一直向前,直到一下情况发生:(1)碰到了block,则停在block前,该block消失;(2)冲出了场地外;(3)到达了终点。改变方向十次以上或者冲出场外都判输,问至少几步能到达终点,无法到达输出-1。

    【思路】

    DFS,往四个方向搜索,每次不断向前直到出现如上三种情形,并根据三种情形操作,有点类似于模拟。回溯的时候犯的小错误记在代码的注释里面了。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 using namespace std;
     5 const int MAXN=20+5;
     6 const int INF=0x7fffffff;
     7 int map[MAXN][MAXN];
     8 int dx[4]={0,0,1,-1};
     9 int dy[4]={1,-1,0,0};
    10 int line,row,sx,sy;
    11 int ans;
    12 
    13 void dfs(int x,int y,int step)
    14 {
    15     if (step>10 || step>ans) return;
    16     for (int i=0;i<4;i++)
    17     {
    18         int tx=x+dx[i],ty=y+dy[i];
    19         if (map[tx][ty]==1) continue;
    20         while (tx<line && ty<row && tx>=0 && ty>=0 && map[tx][ty]!=3 && map[tx][ty]!=1)
    21         {
    22             tx+=dx[i];
    23             ty+=dy[i];
    24         }
    25         if (tx==line || ty==row || tx<0 || ty<0) continue;
    26         /*冲出场外判为输*/ 
    27         
    28         if (map[tx][ty]==3)
    29         {
    30             /*到达终点记录最小步数*/
    31             if (step<ans) ans=step;
    32             continue;
    33         }
    34         
    35         else if (map[tx][ty]==1)
    36         {
    37             /*碰到障碍物则停在障碍物前,并清除障碍物*/
    38             map[tx][ty]=0;
    39             dfs(tx-dx[i],ty-dy[i],step+1);
    40             map[tx][ty]=1;
    41 /* 42 map[tx][ty]=0; 43 tx-=dx[i]; 44 ty-=dy[i]; 45 dfs(tx,ty,step+1); 46 map[tx+dx[i]][ty+dy[i]]=1;←如上情况是,回溯时千万不要忘记把倒退的步骤加回去 47 */

    48 } 49 } 50 } 51 52 int main() 53 { 54 while (scanf("%d%d",&row,&line)) 55 { 56 if (row==line && line==0) break; 57 for (int i=0;i<line;i++) 58 for (int j=0;j<row;j++) 59 { 60 scanf("%d",&map[i][j]); 61 if (map[i][j]==2) 62 { 63 sx=i;sy=j; 64 map[i][j]=0; 65 } 66 } 67 ans=INF; 68 dfs(sx,sy,1); 69 if (ans!=INF) cout<<ans<<endl; 70 else cout<<-1<<endl; 71 } 72 return 0; 73 }
  • 相关阅读:
    keras后端设置【转载】
    NN中的激活函数【转载】
    关于范数【转载】
    常用范数公式【转载】
    Tf中的SGDOptimizer学习【转载】
    亲和串 kmp
    kmp基础 ekmp
    Number Sequence kmp
    P1052 过河 线性dp
    P1074 靶形数独 dfs回溯法
  • 原文地址:https://www.cnblogs.com/iiyiyi/p/4712788.html
Copyright © 2011-2022 走看看