java图遍历求最长路径_如何在Java中使用递归实现矩阵中最长路径的返回
我正試圖用遞歸來解決這個問題。
問題是:對于二維正整數數組,我如何返回最長路徑(步驟),以便最長路徑的每個單元格中的值是從整數的降序序列開始的,并且每個單元格和單元格之間的差異是一個給定的數字(num)。
假定
n
是單元格的值,所以(
n
-num)是一個正數(不是零)。
我不能使用任何循環(for,while,…等)
方法:
public static int longestPath(int matrix[][],int number){...
return(__overloading__);
}
例如
:
int number=1;
int [][]matrix ;
matrix = new int[][]{{8, 15, 20, 33, 35},
{60, 59, 58, 32, 31},
{59, 17, 57, 56, 55},
{55, 15, 13, 58, 16}};
System.out.print(" longestPath= "+ longestPath(matrix, num));
}
如果我們尋找有差異的最長路徑
數
= 1
1-在細胞中
矩陣〔0〕〔3〕
路徑長度為3,此路徑中的值為33->32->31以
矩陣〔1〕〔4〕
2-細胞
矩陣〔1〕〔0〕
]路徑長度為6,路徑60->59->58->57->56->55中的值以
矩陣〔2〕〔4〕
細胞中的3
矩陣〔1〕〔0〕
路徑長度為2,此路徑中的值為60->59以
矩陣〔2〕〔0〕
因此,該方法必須返回最長路徑開關6
如果我們尋找有差異的最長路徑
數
= 2
1-在細胞中
矩陣〔2〕〔1〕
路徑長度為3,此路徑中的值為17->15->13以
矩陣〔3〕〔2〕
方法必須返回其3的最長路徑。
我的非工作代碼:
public class CC {
public static int longestPath (int arr[][] , int num){
return longestPath(arr,arr.length-1,arr[0].length-1,num,0);
}
public static int longestPath (int arr[][],int rows,int cols,int num,int max){
System.out.println("==> longestPath() arr value=" + arr[rows][cols] + " rows:"+rows + " cols:"+cols + " max:"+max);
if (cols ==0 && rows != 0 ){
cols = arr[0].length-1;
rows--;
}
if (rows ==0 && cols==0 ){
System.out.println("finish");
return 0;
}
int steps = searchPath(arr,rows,cols,num,max);
if (steps > max) max=steps;
longestPath(arr,rows,cols-1,num,max);
return max ;
}
public static int searchPath(int arr[][],int rows,int cols,int num ,int counter){
System.out.println("searchPath() arr value=" + arr[rows][cols] + " rows:"+rows + " cols:"+cols);
int left=1,right=1,up=1,down=1;
if ((cols != 0) && arr[rows][cols] - num == arr[rows-1][cols] ){ // checking up cell
counter++;
up = searchPath(arr,rows-1,cols,num,counter);
}
if ((rows != arr.length-1) && arr[rows][cols] - num == arr[rows+1][cols] ){ // checking down cell
counter++;
down = searchPath(arr,rows+1,cols,num,counter);
// return counter;
}
if ((cols != 0) && arr[rows][cols] - num == arr[rows][cols-1]){ // checking left cell
counter++;
left = searchPath(arr,rows,cols-1,num,counter);
//return counter;
}
if ((cols != arr[0].length-1) && arr[rows][cols] - num == arr[rows][cols+1] ){ //checking right cell
counter++;
right = searchPath(arr,rows,cols+1,num ,counter);
//return counter;
}
if ((left > right) && (left > up) && (left > down)) // if left cell is bigger than all other direction return left
return left;
if ((right > left) && (right > up) && (right > down))
return right;
if ((down > up) && (down > right) &&( down > left))
return down;
if ((up> down) && (up > right) && (up>left))
return up;
return 0;
}
}
在編寫代碼時,我遇到了很多運行問題
我做錯什么了?
提前謝謝
總結
以上是生活随笔為你收集整理的java图遍历求最长路径_如何在Java中使用递归实现矩阵中最长路径的返回的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: delphi里用java_如何在整个De
- 下一篇: java双机调度_Haproxy+kee