java - 在矩阵中找到递减序列的最长斜率的问题
问题描述
我在课程中被要求解决以下问题:
给定一个 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,有人可以尝试看看问题吗?我无法使用我的调试器找到它。我很感激你的帮助和帮助。
解决方案
推荐阅读
- javascript - 如何使用 discord.js 进行简单的全局冷却
- office365 - 来自 Jira 电子邮件的 DisplayName (Exchange Online)
- python - 无法将 altair 可视化作为弹出窗口插入到叶地图中
- c++ - 为什么我在这个 Karatsuba 乘法中出现逻辑错误?
- react-native - animatable 不断使视图增长
- fluentvalidation - 如何使用 FluentValidation 验证集合中的不同类型?
- python - 如何在不将多个标题副本创建到行中的情况下附加到 csv 文件?
- delphi - 如何通过 ScanLine 复制灰度位图
- groovy - groovy 遍历键和值列表
- tsql - 按分区准确排序日期名称