我在课程中被要求解决以下问题:
给定一个由m * n个正数组成的矩阵,“斜率”是一系列k单元,每个单元与其前一个相邻(上,右,左或下但不对角),因此值是递减的差异为“ num”的发票系列(已提供num,num> 0)。
我需要使用递归函数在矩阵中找到最长的斜率。 这是我的代码:
public static int longestSlope(int[][] mat, int num){
return longestSlope(mat,num,0,0, mat[0][0]);
}
public static int longestSlope(int[][] mat, int num, int row, int col, int prev_val){
//This function runs over each cell in the matrix
if (row < 0 || row >= mat.length || col < 0 || col >= mat[0].length)
return 0;
int right, down;
right = longestSlope1(mat, num, row, col + 1, mat[row][col]);
down = longestSlope1(mat, num, row + 1, col, mat[row][col]);
return Math.max(right, down);
}
public static int longestSlope1(int[][] mat, int num, int row, int col, int prev_val){
//This function runs over each cell and checks the "Slopes"
//that begin from that particular cell
if (row < 0 || row >= mat.length || col < 0 || col >= mat[0].length)
return 0;
int right = 1, down = 1, left = 1, up = 1;
if(mat[row][col] == prev_val - num) {
right += 1 + longestSlope1(mat, num, row, col + 1, mat[row][col]);
down += 1 + longestSlope1(mat,num,row + 1, col, mat[row][col]);
left += 1 + longestSlope1(mat, num, row, col - 1, mat[row][col]);
up += 1 + longestSlope1(mat, num, row - 1, col, mat[row][col]);
}
else return 0;
return Math.max(Math.max(down, up), Math.max(right, left));
}
我的实际结果为0,有人可以尝试看看问题吗?我无法使用调试器找到它。感谢您的帮助和协助。