[英]Find all paths from top left to bottom right problem. Recursive solution with array as parameter output explanation
[英]Storing all diagonals from top right to bottom left in array
我試圖將矩陣中從右上角到左下角的所有值存儲在一個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];
}
}
}
一種解決方案是遍歷一個矩陣,在該矩陣中考慮矩陣外的位置,但排除每個索引越界。
static int[] getDiagonals(int[][] mat) {
int diagonal[] = new int[mat.length * (mat[0].length)];
int index = 0;
int yStart = -mat[0].length;
for (int y = yStart; y < mat.length; y++) {
for (int x = 0; x < mat[0].length; x++) {
if (y + x >= 0 && y + x < mat.length) {
diagonal[index++] = mat[y+x][x];
}
}
}
return diagonal;
}
可能不是最佳的,因為您有效地遍歷了幾乎兩倍大小的矩陣,但它非常直觀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.