首页 > 编程语言 > 详细

啊哈算法第四章第二节解救小哈Java实现

时间:2017-05-16 10:18:03      阅读:262      评论:0      收藏:0      [点我收藏+]
package corejava;



public class FourTwo {
    static int m;//(m,n)为几行几列
    static int n;
    static int p;//(p,q)为终点
    static int q;
    static int min=9999;
    static int [][]a=new int [51][51];//存放地图
    static int [][]b=new int [51][51];//存放路径
    static String []record=new String[9999];
    
    public static void dfs(int x,int y,int step)
    {
        int [][]next={{0,1},{1,0},{0,-1},{-1,0}};
        if(x==p&y==q)
        {
            System.out.println("step"+step);
             for(int i=0;i<step;i++)
             {
                 System.out.print(record[i]);
             }
             System.out.println(" ");
            
            if(step<min)
            {
                min=step;
                
            }
            return;
            
        }
        for(int k=0;k<4;k++)
        {
            int tx=x+next[k][0];
            int ty=y+next[k][1];
            if(tx<0||tx>=m||ty<0||ty>=n)
            {
                continue;
                
            }
            if(a[tx][ty]==0&b[tx][ty]==0)
            {
                
                record[step]="("+tx+","+ty+")";
                
                
                
                b[tx][ty]=1;
                dfs(tx,ty,step+1);//若这行代码变为step++;dfs(tx,ty,step);则改变了for循环里step的值,就会出问题
                b[tx][ty]=0;    
            }
            
            
        }
        return;
    }
    public static void main(String []args)
    {
        
         m = 5;
         n = 4;
         int startx=0;
         int starty=0;
         p=3;
         q=2;
         b[startx][starty]=1;
         record[0]="("+0+","+0+")";
         a[0][2]=1;
         a[2][2]=1;
         a[3][1]=1;
         a[4][3]=1;
    
        
         dfs(startx,starty,0);
         System.out.println("min"+min);
        
        
        
    }

}

这里感觉获取输入太麻烦,直接设置了固定值。同时dfs(tx,ty,step+1);这里很困扰我,开始没有考虑step在循环中用到,step=step+1后改变了循环里step的值,查询了好久才知道出错的原因。

 

啊哈算法第四章第二节解救小哈Java实现

原文:http://www.cnblogs.com/xiaoxian7/p/6860002.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!