啊哈算法第四章第三节 层层递进-广度优先搜索 java实现

Posted on 2017-05-16 10:25  小线7  阅读(369)  评论(0)    收藏  举报
package corejava;

public class FourThree {
    static int [][]a=new int[50][50];
    static int [][]b=new int[50][50];
    
    static int m;
    static int n;
    static int p;
    static int q;
    
    public static void dfs(int step) {
        System.out.println("dfs"+step);
        int [][]next={{0,1},{1,0},{0,-1},{-1,0}};
        if(b[p][q]>0)
            return;
        int c=0;
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
            {
                //System.out.print("b["+i+"]["+j+"]"+b[i][j]);
                if(b[i][j]==step+1)
                {
                    
                    for(int k=0;k<4;k++)
                    {
                        int tx=i+next[k][0];
                        int ty=j+next[k][1];
                        if(tx<0||tx>m||ty<0||ty>n)
                        {
                            continue;
                            
                        }
                        if(a[tx][ty]==0&b[tx][ty]==0)
                        {
                            c++;
                            b[tx][ty]=step+2;
                            
                            
                            
                            System.out.print("step"+(step+1) +"("+tx+","+ty+")");
                            if(tx==p&ty==q)
                            {
                                System.out.println("step"+step);
                                
                                 System.out.println(" ");
                                
                                
                                return;
                                
                            }
                            
                            
                            
                            
                            
                        }
                        
                        
                    }
                }
            }
        if(c==0)
            return;
        dfs(step+1);
    
        
    }
    public static void main(String []args)
    {
        
         m = 5;
         n = 4;
         int startx=0;
         int starty=0;
         p=3;
         q=2;
         b[startx][starty]=1;
         
         a[0][2]=1;
         a[2][2]=1;
         a[3][1]=1;
         a[4][3]=1;
    
        
         dfs(0);
        
        
        
        
    }
    
    
    

}

 

这里没有用例子里的结构体,采用了一个数组b【】【】存放该位置可几步到达,因为数组内容默认为0,固存放的为可到达步数加一。一个一个往下延伸。但是这里用到循环来查找,当地图比较大,循环次数会很多。

 

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3