gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:23:22 27 4
gpt4 key购买 nike

我有一个家庭作业,我必须找到一个递归函数,它获取一个二维矩阵和矩阵中的行数并返回 true/false 如果矩阵的对角线有字母 a b c 序列,

想不出解决办法

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]

/image/Z6qmn.png

最佳答案

这非常简单。只需检查每次迭代当前值是否等于前一个 +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);
}

关于java - 是否有递归检查矩阵对角线上是否有字母序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56621071/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com