啊哈演算法第四章第二節解救小哈Java實現

來源:互聯網
上載者:User

標籤:blog   step   ext   starty   start   固定   next   core   問題   

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實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.