我试图将所有值存储在矩阵中,从右上到左下,并将它们存储在中array
。
int matrixSample [][] = {
{6,4,1,4},
{7,5,4,4},
{4,4,8,3},
{4,4,8,3}
};
输出应为
[4,1,4,4,4,3,6,5,8,3,7,4,8,4,4,4]
我可以得到右下角的对角线
static int[] getAllDiagonalsInMatrix(int matrix[][]){
// Sum of arithmetic progression
int diagonal[] = new int[matrix.length * (matrix.length + 1)*2];
int index = 0;
for(int row = 0; row < matrix.length; row++) {
for(int col = 0; col < matrix[row].length - row; col++) {
diagonal[index++] = matrix[row + col][col];
}
}
return diagonal;
}
通过在上面的循环中进行调整,是否可以使用相同的两个循环?
好的,这是我对您的问题的思考过程。但是,我将打印值而不是收集值,以使它对我来说更容易一点,并使解决方案易于阅读。
首先,如何得到对角线?我们需要经常执行此操作,因此让我们开始为此创建一个函数。也许我们可以通过对角线的左上角并从那里去。
public void getDiagonal(int[][] array, int row, int col) {
// While row and col are within the bounds of the array
while (row < array.length && col < array[row].length) {
// Print element in diagonal
System.out.println(array[row][col]);
// Diagonal moves from top-left to bottom-right
row++;
col++;
}
}
现在我们有了一个获取对角线的函数,我们只需要一种调用它的方法。本质上,我们只需要遵循从右上角到左上角再到左下角的L形。
// Get diagonals starting in the first row with a column > 0
for (int col = array.length - 1; col > 0; col--) {
getDiagonal(array, 0, col);
}
// Get all diagonals starting from the left most column
for (int row = 0; row < array.length; row++) {
getDiagonal(array, row, 0);
}
现在,我们有了一种遍历值的可行方法,我们可以重写它以将值保存到数组中。您现在也可以选择完全删除该功能,因为您已经有了一个过程。
编辑:我几乎忘记了,但是您正在寻找的数学解决方案如下。
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array.length; col++) {
// Index along diagonal
int diagonal = Math.min(row, col);
// Which part of L contains value
if (col >= row) {
int start = array.length - 1 - (col - row);
int passed = start * (start + 1) / 2;
solution[passed + diagonal] = array[row][col];
} else {
int start = array.length - 1 - (row - col);
int passed = array.length * array.length - 1 - start * (start + 1) / 2; solution[passed - array.length + 1 + row] = array[row][col];
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句