POJ 3009 Curling 2.0(DFS)

题目链接

做了好久,看题,想用BFS还是DFS,写出来各种单步,最后1Y还是比较高兴。。这种找最短步数一般是BFS的,但是发现状态一直在变,用DFS写起来比较方便,把题目看清楚就OK了。

解释一下题意:一个球从起点出发,到终点,最少需要人动几次,规则,如果出了棋盘,游戏结束,如果碰到木块,木块消失,人为可以选择方向,大体就是这样。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <map>
 5 #include <cstring>
 6 #include <cmath>
 7 using namespace std;
 8 int ans;
 9 int a[4] = {0,0,1,-1};
10 int b[4] = {1,-1,0,0};
11 int p[51][51],n,m;
12 int judge(int x,int y)
13 {
14     if(x <= n&&x >= 1&&y <= m&&y >= 1)
15         return 1;
16     else
17         return 0;
18 }
19 void dfs(int x,int y,int step)
20 {
21     int i,r,c;
22     if(step > 10||step > ans) return;
23     if(p[x][y] == 3)
24     {
25         if(ans > step)
26             ans = step;
27         return ;
28     }
29     for(i = 0; i < 4; i ++)
30     {
31         r = x;
32         c = y;
33         while(p[r][c] == 0)
34         {
35             r += a[i];
36             c += b[i];
37         }
38         if(p[r][c] == 3)
39         {
40             dfs(r,c,step+1);
41             return ;
42         }
43         if(x+a[i] == r&&y+b[i] == c)
44             continue;
45         if(judge(r,c))
46         {
47             p[r][c] = 0;
48             dfs(r-a[i],c-b[i],step+1);
49             p[r][c] = 1;
50         }
51     }
52 }
53 int main()
54 {
55     int i,j,sr,sc;
56     while(scanf("%d%d",&m,&n)!=EOF)
57     {
58         if(m == 0&&n == 0) break;
59         ans = 10000;
60         memset(p,0,sizeof(p));
61         for(i = 1; i <= n; i ++)
62         {
63             for(j = 1; j <= m; j ++)
64             {
65                 scanf("%d",&p[i][j]);
66                 if(p[i][j] == 2)
67                 {
68                     sr = i;
69                     sc = j;
70                 }
71             }
72         }
73         for(i = 1; i <= n; i ++)
74         {
75             p[i][0] = -1;
76             p[i][m+1] = -1;
77         }
78         for(i = 1; i <= m; i ++)
79         {
80             p[0][i] = -1;
81             p[n+1][i] = -1;
82         }
83         p[sr][sc] = 0;
84         dfs(sr,sc,0);
85         if(ans == 10000)
86         printf("-1\n");
87         else
88         printf("%d\n",ans);
89     }
90     return 0;
91 }

 

posted @ 2013-01-19 11:04  Naix_x  阅读(335)  评论(0编辑  收藏  举报