POJ3009(DFS)

两点:1.出边界即无效。

   2.有障碍物相邻不能直接抛向障碍物。

题目好难理解哦,有道都派不是用场。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 #include <cstring>
 5 #include <algorithm>
 6 using namespace std;
 7 int n,m,t, vis[45][45], sum,flag;
 8 int a[45][45],start_x,start_y;
 9 int step[4][2] = {-1,0,1,0,0,-1,0,1};
10 void dfs(int k,int h,int x,int y)//k为方向,h为步数。
11 {
12     if (h > 10||h>=sum)
13         return;
14     if(a[x][y]==3)
15     {
16         flag = 1;
17         sum=min(sum, h);
18         return;
19     }
20     else if (a[x][y] == 1)
21     {
22         a[x][y] = 0;
23         dfs(-1,h,x-step[k][0],y-step[k][1]);
24         a[x][y] = 1;
25         return;
26     }
27     if (k == -1)
28     {
29         int next_x, next_y;
30         for (int i = 0; i < 4; i++)
31         {
32             next_x = x + step[i][0];
33             next_y = y + step[i][1];
34             if (next_x >= 0 && next_y < m && next_y >= 0 && next_x < n&&a[next_x][next_y]!=1)
35             {
36                 dfs(i, h + 1, next_x, next_y);
37             }
38         }
39     
40     }
41     else
42     {
43         int next_x = x + step[k][0], next_y = y + step[k][1];
44         if (next_x >= 0 && next_x < n&&next_y >= 0&&next_y<m)
45             dfs(k, h, next_x, next_y);
46     }
47 
48 }
49 int main(int argc, char *argv[])
50 {
51     while (cin >> m >> n)
52     {
53         if (m == 0 && n == 0)
54             break;
55         memset(a, 0, sizeof(a));
56         for (int i = 0; i < n; i++)
57         {
58             for (int j = 0; j < m; j++)
59             {
60                 cin >> a[i][j];
61                 if (a[i][j] == 2)
62                 {
63                     start_x = i;
64                     start_y = j;
65                 }
66             }
67                 
68         }
69         flag = 0; sum = 999999;
70         dfs(-1,0,start_x,start_y);
71         if (flag)
72             printf("%d\n", sum);
73         else
74             printf("-1\n");
75     }
76 }

猜你喜欢

转载自www.cnblogs.com/huluxin/p/9299308.html