POJ 3009-Curling 2.0(DFS)

http://poj.org/problem?id=3009

在方格中给定起始点和目标点问到达目标点需要多少步,如果不能到达或者超过10步输出-1。1代表障碍物,0代表空地,2代表起始点,3代表终点。

移动规则:只能按x轴或y轴移动(4个方向) 如果某方向下一步就是障碍物则不能像这方向移动,如果某方向没有障碍物则可以一直沿这个方向移动,遇到障碍物的话,会停留在障碍物的前一个格子上,同时障碍物会消失。

这题跟普通的dfs不同之处在于可以沿某方向一直走下去。需要特殊处理。

 1 #include <iostream>
 2 #include <cstdio>
 3 //#include <cmath>
 4 #include <vector>
 5 #include <cstring>
 6 #include <string>
 7 #include <algorithm>
 8 #include <string>
 9 #include <set>
10 #include <functional>
11 #include <numeric>
12 #include <sstream>
13 #include <stack>
14 #include <map>
15 #include <queue>
16 
17 #define CL(arr, val)    memset(arr, val, sizeof(arr))
18 
19 #define ll long long
20 #define inf 0x7f7f7f7f
21 #define lc l,m,rt<<1
22 #define rc m + 1,r,rt<<1|1
23 #define pi acos(-1.0)
24 
25 #define L(x)    (x) << 1
26 #define R(x)    (x) << 1 | 1
27 #define MID(l, r)   (l + r) >> 1
28 #define Min(x, y)   (x) < (y) ? (x) : (y)
29 #define Max(x, y)   (x) < (y) ? (y) : (x)
30 #define E(x)        (1 << (x))
31 #define iabs(x)     (x) < 0 ? -(x) : (x)
32 #define OUT(x)  printf("%I64d
", x)
33 #define lowbit(x)   (x)&(-x)
34 #define Read()  freopen("a.txt", "r", stdin)
35 #define Write() freopen("dout.txt", "w", stdout);
36 #define maxn 1000000000
37 #define N 110
38 using namespace std;
39 
40 int x1,y1,step;
41 int h,w,field[25][25];
42 int dir[4][2]={-1,0,1,0,0,-1,0,1};
43 void dfs(int x,int y,int cnt)
44 {
45     if(cnt>10) return;  //剪枝
46     for(int i=0;i<4;i++)
47     {
48         int xx=x+dir[i][0];
49         int yy=y+dir[i][1];
50         if(!(xx>=0&&xx<h&&yy>=0&&yy<w)||field[xx][yy]==1) continue;
51         while(!field[xx][yy])   //沿这个方向一直走,直到遇到障碍物
52         {
53             xx+=dir[i][0];
54             yy+=dir[i][1];
55         }
56         //printf("%d %d
",xx,yy);
57         if(xx>=0&&xx<h&&yy>=0&&yy<w) //同时需要判断是不是出界
58         {
59             if(field[xx][yy]==3)
60             {
61                 step=min(step,cnt);
62             }
63             else if(field[xx][yy]==1)
64             {
65                 field[xx][yy]=0;  //障碍物消失
66                 xx-=dir[i][0];
67                 yy-=dir[i][1];
68                 dfs(xx,yy,cnt+1);
69                 field[xx+dir[i][0]][yy+dir[i][1]]=1; //回溯
70             }
71         }
72     }
73 }
74 int main()
75 {
76     //freopen("a.txt","r",stdin);
77     while(~scanf("%d%d",&w,&h)&&w+h)
78     {
79         for(int i=0;i<h;i++)
80             for(int j=0;j<w;j++)
81             {
82                 scanf("%d",&field[i][j]);
83                 if(field[i][j]==2)
84                 {
85                     x1=i;
86                     y1=j;
87                     field[i][j]=0;
88                 }
89             }
90         step=11;
91         dfs(x1,y1,1);
92         if(step>10) printf("-1
");
93         else
94         printf("%d
",step);
95     }
96    return 0;
97 }
View Code
原文地址:https://www.cnblogs.com/nowandforever/p/4374400.html