2013-06-23 51 views
0

我想寫一個使用遞歸方法的程序查找從兩維數組開始到最後的路徑數。步驟應從[0] [0]開始直到結束。數組由0到99之間的整數填充。例如,如果[0] [0]是21,下一步可能是[0 + 2] [0 + 1]或[0 + 1] [0] [0] [0] [0] [0] [1] 0 + 2]。 該方法應返回不同路徑的數量以達到最終點。修復遞歸方法

這裏是我的代碼:

在comilation一個具有溢出時方法獲取[] []數組

 public class two 
     { 
      int[][] _my=new int[0][0]; 
      public two() 
     { 
     } 
     static int count=0; 
     public static int count; 

ountPath(int[][] mat) 
    { 
     int nextX=0; 
     int nextY=0; 
     int current=mat[0][0]; 
     if (current<=9) 
     { 
      nextX=current; 
      nextY=current; 
      if (checkBorders(0,0,nextX,nextY,mat)==0) 
      { 
       return 0; 
      } 
     } 
     else 
     { 
      nextX=(int)current/10; 
      nextY=current%10; 
      if (checkBorders(0,0,nextX,nextY,mat)==0) 
      { 
       return 0; 
      } 
     } 
     countPath(mat,nextX,nextY); 
     countPath(mat,nextY,nextX); 
     return count; 
    } 

    public static int countPath(int[][] mat,int x,int y) 
    { 
     int current=mat[x][y]; 
     int nextX=0; 
     int nextY=0; 
     int terminate=0; 
     if (current<=9) 
     { 
      nextX=current; 
      nextY=current; 
      if (checkBorders(x,y,nextX,nextY,mat)==0) 
      { 
       return 0; 
      } 
     } 
     else 
     { 
      nextX=(int)current/10; 
      nextY=current%10; 
      if (checkBorders(x,y,nextX,nextY,mat)==0) 
      { 
       return 0; 
      } 
     } 

     if (((mat.length-1)==nextY)&&((mat[0].length-1)==nextX)) 
     { 
      terminate=1; 
     } 

     if (terminate==1) 
      count++; 
     else 
     { 
     countPath(mat,nextX,nextY); 
     countPath(mat,nextY,nextX); 
     } 
     return count; 
    } 

    public static int checkBorders(int x,int y,int x1,int y1,int[][] mat) 
    { 
     int maxX=mat[0].length; 
     int maxY=mat.length; 
     if ((x+x1)>maxX) 
      return 0; 
     else if ((y+y1)>maxY) 
      return 0; 
     else return 1; 
    } 

} 

請幫我修復代碼。

+1

它不起作用?計數是一個靜態變量嗎?順便說一句,在Java中,你可以使用'布爾' – UmNyobe

+0

如果代碼是自包含的,不僅可以說出問題的出處,還可以發佈完整的代碼。 – Sandro

+0

是的,我使用靜態計數變量。 – user2513643

回答

0

你必須添加一個布爾數組,你將存儲哪個狀態已經被訪問過。現在,你可能會到以下情形:

您在狀態A. 從狀態的,你可以去國家B和C. 從狀態B,你可以去到狀態A < - 這將是無限循環。

此外,記憶將大大提高計算速度。

希望我幫你。