• 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
    
    
  • 相关阅读:
    2019-06-2 java学习日记
    2019-06-1 java学习日记
    2019-05-31 java学习日记
    2019-05-30 java学习日记
    2019-05-29 java学习日记
    2019-05-28 java学习日记
    2019-05-27 java学习日记
    2019-06-03 Java学习日记 day24 多线程
    2019-06-02 Java学习日记 day23 递归练习
    2019-06-01 Java学习日记 day22 io其他流
  • 原文地址:https://www.cnblogs.com/ssf-xiaoban/p/9437835.html
Copyright © 2020-2023  润新知