POJ-3009

POJ-3009 冰壶

 题目自行查看:http://poj.org/problem?id=3009

 一道经典搜索题,挺费时间

 注意:输入很坑,先列后行

  dfs不加优化轻松(调了大半天)

 Sample Input

2 1
3 2
6 6
1 0 0 2 1 0
1 1 0 0 0 0
0 0 0 0 0 3
0 0 0 0 0 0
1 0 0 0 0 1
0 1 1 1 1 1
6 1
1 1 2 1 1 3
6 1
1 0 2 1 1 3
12 1
2 0 1 1 1 1 1 1 1 1 1 3
13 1
2 0 1 1 1 1 1 1 1 1 1 1 3
0 0

 Sample Output

1
4
-1
4
10
-1

1
#include<iostream> 2 using namespace std; 3 int a[25][25],n,m,sx,sy,flag=0,ans=99999999; 4 int dx[4]={0,0,1,-1}; 5 int dy[4]={1,-1,0,0}; 6 void dfs(int x,int y,int step) 7 { 8 if(step>=ans||step>=10) return;//超过10步自动结束(题目要求) 9 for(int i=0;i<4;i++) 10 { 11 int tx=x+dx[i]; 12 int ty=y+dy[i]; 13 if(a[tx][ty]==1) continue;//前方砖块continue 14 while(tx>0&&tx<=n&&ty>0&&ty<=m&&a[tx][ty]!=1&&a[tx][ty]!=3) 15 { 16 tx+=dx[i]; 17 ty+=dy[i];//前进 18 }//一直前进,直到砖块或终点 19 if(tx<=0||ty<=0||tx>n||ty>m) continue;//超限continue 20 if(a[tx][ty]==3) 21 { 22 flag=1; 23 ans=step+1;//多走一步 24 return; 25 } 26 else 27 { 28 a[tx][ty]=0; 29 dfs(tx-dx[i],ty-dy[i],step+1);//回溯 30 a[tx][ty]=1; 31 } 32 } 33 return; 34 } 35 int main() 36 { 37 while(cin>>m>>n&&n!=0&&m!=0) 38 { 39 for(int i=1;i<=n;i++) 40 for(int j=1;j<=m;j++) 41 { 42 cin>>a[i][j]; 43 if(a[i][j]==2) 44 { 45 a[i][j]=0;//把起点标注为空地 46 sx=i; 47 sy=j; 48 } 49 } 50 dfs(sx,sy,0); 51 if(flag) cout<<ans<<endl; 52 else cout<<-1<<endl; 53 ans=99999999; 54 flag=0; 55 } 56 }
搜索chishi
 
 

 

转载于:https://www.cnblogs.com/ssf-xiaoban/p/9437835.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值