码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3009 Curing2.0

时间:2015-08-17 21:35:41      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

POJ 3009 Curing2.0

题目:在图里向一个方向发射一颗弹球,弹到石头停下来,石头消失,若弹球紧挨石头则不能发射,中途出界算失败,发射次数不超过十次。求最小发射次数。

思路:还是DFS,由于碰撞后石头会消失,应注意地图的还原。一次发射可能不止一步,加上多种情况。应思路清晰时,对DFS函数细致分类。

 1 #include <iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 const int INF = 1000000;
 5 int dx[4] = {1, -1, 0, 0};
 6 int dy[4] = {0, 0, -1, 1};
 7 int h, w;
 8 int G[23][23];
 9 int min_step;
10 //在DFS的函数参数中加入step可化简思路 
11 void dfs(int x, int y, int step) {
12     int nx, ny;
13     //一个比较好的剪枝 
14     if(step >= 10) return ;
15 
16     for(int d=0; d<4; d++) {
17         nx = x; ny = y;
18         nx = x+dx[d];
19         ny = y+dy[d];
20         //先排除出界和贴墙的情况 
21         if(nx < 0 || ny < 0 || nx >= h || ny >= w) continue ;
22         if(G[nx][ny] == 1) continue;  
23         //这个while的结束分三种情况,之后再对这三种情况进行讨论 
24         while(!(G[nx][ny] == 1 || G[nx][ny] == 3)) {
25             nx += dx[d];
26             ny += dy[d];
27             if(nx < 0 || ny < 0 || nx >= h || ny >= w) break;
28         }
29         //这个判断有必要
30         if(nx < 0 || ny < 0 || nx >= h || ny >= w) continue; 
31 
32         if(G[nx][ny] == 3) {   
33             min_step = min(min_step, step+1);
34         }
35         else if(G[nx][ny] == 1){  
36             G[nx][ny] = 0;
37             dfs(nx-dx[d], ny-dy[d], step+1);
38             //地图的还原,这一步还是很重要的 
39             G[nx][ny] = 1;
40         }
41     }
42 }
43 
44 int main()
45 {
46     int sx, sy;
47     while(cin>>w>>h,w||h)
48     {
49         min_step = INF;
50         for(int i=0; i<h; i++)
51         {
52             for(int j=0; j<w; j++) 
53             {
54                 cin>>G[i][j];
55             }
56         }
57         //查找开关的应用 
58         bool found=false;
59         for(int i=0; i<h; i++) 
60         {
61             for(int j=0; j<w; j++) 
62             {
63                 if(G[i][j] == 2) 
64                 {
65                     sx = i; sy = j;
66                     found=true;
67                     break;
68                 }
69             }
70             if(found)
71             {
72                    break;
73             }
74         }
75         dfs(sx, sy, 0);
76         if(min_step != INF) 
77         {
78             cout<<min_step<<endl;
79         }
80         else 
81         {
82             cout<<-1<<endl;
83         }
84     }
85     return 0;
86 }

 

POJ 3009 Curing2.0

标签:

原文地址:http://www.cnblogs.com/xlsryj/p/4737435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!