是否有递归检查矩阵对角线是否有字母序列

时间:2019-06-16 17:23:05

标签: java

我完成了一项作业,我必须找到一个递归函数,该函数获取2D矩阵和矩阵中的行数并返回true / false,如果矩阵的对角线包含字母abc,

想不出解决方案

public static void main(String[] args) {
    char[][] mat = new char[5][5];

    for (int i = 0; i < mat.length; i++) {
        for (int j = 0; j < mat[i].length; j++)
            mat[i][j] = (char) (int) ((Math.random() * 26) + 'a');
    }

    for (int i=0 ; i <mat.length ; i++)
        mat[i][i] = (char)('a' + i);
    //mat[2][2] = 'b';

    for (int i = 0; i < mat.length; i++) {
        for (int j = 0; j < mat[i].length; j++)
            System.out.print(mat[i][j] + " ");
        System.out.println();
    }

    System.out.println(isDiagonalLettersSequence(mat, mat.length));

}[Here are two examples that I hope will help me explain myself][1]

https://i.stack.imgur.com/Z6qmn.png

1 个答案:

答案 0 :(得分:0)

这很简单。只需检查每次迭代是否当前值等于先前的+1:

public static boolean isDiagonalHasSequence(char[][] matrix) {
    return isDiagonalHasSequence(matrix, 0);
}

private static boolean isDiagonalHasSequence(char[][] matrix, int row) {
    if (row > 0 && row < matrix.length) {
        // check diagonal \
        if (matrix[row][row] != matrix[row - 1][row - 1] + 1)
            return false;
        // check diagonal /
        if (matrix[row][matrix.length - row - 1] != matrix[row - 1][matrix.length - row - 2] + 1)
            return false;
    }

    return row == matrix.length || isDiagonalHasSequence(matrix, row + 1);
}