java - 在数组中存储从右上角到左下角的所有对角线
问题描述
我正在尝试将矩阵中的所有值从右上角存储到左下角,并将它们存储在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];
}
}
}
推荐阅读
- django - 如何让用户在线支付费用
- python - Python - 根据 JSON 中的值从 JSON 中删除重复元素
- c# - 如何在检查器中使用字符串插值?
- typescript - 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引
- javascript - 如何通过搜索栏 React Native 搜索 FlatList?
- html - CSS网格中列的反转顺序
- c - 带有 Zip 插件的 Cordova iOS 应用程序编译 - 未找到 aes/aes.h
- javascript - 如果 JavaScript 中有条件,如何使用 forEach 循环返回 true
- python - 在 python 中运行函数后,切片对象作为参数没有改变
- laravel - 使用带有 Laravel eloquent 和多个 where 子句的 Haversine 公式