POJ 3009

题意:已知起点和终点,求石子从起点到达终点的最短路,如果无法到达,则输出-1。石子移动的具体规则如下:
   1、开始时,石子在起点s处
   2、运动方向可以是水平或垂直的,不能斜方向运动
   3、最开始的时候,你可以将石子向上下左右任意一个方向抛,如果与它相邻的点是障碍物的话除外
   4、一旦石子开始运动,有三种可能:
      a、遇到障碍物,石子会停在障碍物的前一格,障碍物会消失
      b、如果出界,游戏失败
      c、到达终点,游戏结束并成功
   5、如果移动的次数超过10次,将认为游戏是失败的

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cctype>
 5 #include <cmath>
 6 #include <time.h>
 7 #include <string>
 8 #include <map>
 9 #include <stack>
10 #include <set>
11 #include <queue>
12 #include <vector>
13 #include <algorithm>
14 #include <iostream>
15 using namespace std;
16 typedef long long ll;
17 typedef pair<int,int> P;
18 #define PI acos( -1.0 )
19 const double E = 1e-8;
20 const int INF = 0x7fffff;
21 const int NO = 105;
22 int a[NO][NO];
23 int n, m, ans;
24 int bi, bj;
25 int dir[][2] = { {-1,0}, {1,0}, {0,-1}, {0,1} };
26 
27 bool judge( int x, int y )
28 {
29     if( x >= 0 && y >= 0 && x < n && y < m )
30         return true;
31     return false;
32 }
33 
34 void dfs( int x, int y, int num )
35 {
36     if( num >= 10 || num > ans )
37         return;
38     for( int i = 0; i < 4; ++i )
39     {
40         int dx = x + dir[i][0];
41         int dy = y + dir[i][1];
42         if( judge( dx, dy ) && a[dx][dy] == 3 )
43         {
44             if( ans > num+1 && num < 10 )
45                 ans = num + 1;
46             return;
47         }
48         if( judge( dx, dy ) && a[dx][dy] == 0 )
49         {
50             bool flag = true;
51             while( a[dx][dy] == 0 )
52             {
53                 dx += dir[i][0];
54                 dy += dir[i][1];
55                 if( !judge( dx, dy ) ) {
56                     flag = false;
57                     break;
58                 }
59                 if( a[dx][dy] == 3 )
60                 {
61                     if( ans > num+1 && num <= 9 )
62                         ans = num + 1;
63                     return;
64                 }
65             }
66             if( flag )
67             {
68                 a[dx][dy] = 0;
69                 dfs( dx-dir[i][0], dy-dir[i][1], num+1 );
70                 a[dx][dy] = 1;
71             }
72         }
73     }
74 }
75 
76 int main()
77 {
78     while( ~scanf( "%d%d", &m, &n ) && n+m )
79     {
80         for( int i = 0; i < n; ++i )
81             for( int j = 0; j < m; ++j )
82             {
83                 scanf( "%d", &a[i][j] );
84                 if( a[i][j] == 2 )
85                 {
86                     a[i][j] = 0;
87                     bi = i;
88                     bj = j;
89                 }
90             }
91         ans = INF;
92         dfs( bi, bj, 0 );
93         if( ans != INF )
94             printf( "%d
", ans );
95         else
96             puts( "-1" );
97     }
98     return 0;
99 }
View Code
原文地址:https://www.cnblogs.com/ADAN1024225605/p/4092190.html