首页 > 解决方案 > 在数组中存储从右上角到左下角的所有对角线

问题描述

我正在尝试将矩阵中的所有值从右上角存储到左下角,并将它们存储在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;
}

这甚至可以通过在上面的循环中进行调整来使用相同的两个循环吗?

标签: java

解决方案


好的,这是我对您的问题的思考过程。但是,我将打印值而不是收集它们,以使我更轻松并保持解决方案易于阅读。

首先,如何获得对角线?我们需要经常这样做,所以让我们先为此创建一个函数。也许我们可以通过对角线的左上角,然后从那里走。

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];
        }
    }
}

推荐阅读