首页 > 解决方案 > 在矩阵中找到递减序列的最长斜率的问题

问题描述

我在课程中被要求解决以下问题:

给定一个 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,有人可以尝试看看问题吗?我无法使用我的调试器找到它。我很感激你的帮助和帮助。

标签: javamatrix

解决方案


推荐阅读