gpt4 book ai didi

java - 二维数组对角填充

转载 作者:太空狗 更新时间:2023-10-29 22:38:42 25 4
gpt4 key购买 nike

1 2 3
4 5 6
7 8 9

这是我的普通数组,但我需要像这样对角排列

1 2 4
3 5 7
6 8 9

这是使它工作的非常愚蠢的方法,但即使它不起作用,因为我找不到第二列元素。

for (i = 0; i < arr.length; ++i) {
for (n = 0; n < arr[0].length; ++n) {
if (i == 0 && n == 0){
arr[i][n] = 0;
} else if (i == 0 && n == 1) {
arr[i][n] = 2;
} else if (i == 1 && n == 0) {
arr[i][n] = 3;
} else if (n == 0) {
arr[i][n] = arr[i - 1][n] - arr[i - 2][n] + 1 + arr[i - 1][n];
} else {
arr[i][n] = arr[i][n - 1] - arr[i][n - 2] + 1 + arr[i][n - 1];
}
}
}

最佳答案

好吧,如果您要为该填充模式枚举索引,您会得到

0,0
1,0
0,1
2,0
1,1
0,2
2,1
1,2
2,2

因此,您需要遍历两个索引的总数。即加总。如您所见,0,0 总计 0,1,00,1 总计 1,依此类推。给我们这样的东西:

0 1 2
1 2 3
2 3 4

要迭代这种对角线模式,我们可以执行以下操作:

// set up your matrix, any size and shape (MxN) is fine, but jagged arrays will break
int[][] matrix = {{0,0,0},{0,0,0},{0,0,0}};

// number is the value we will put in each position of the matrix
int number = 1;

// iterate while number is less than or equal to the total number of positions
// in the matrix. So, for a 3x3 matrix, 9. (this is why the code won't work for
// jagged arrays)
for (int i = 0; number <= matrix.length * matrix[0].length; i++) {
// start each diagonal at the top row and from the right
int row = 0;
int col = i;

do {
// make sure row and length are within the bounds of the matrix
if (row < matrix.length && col < matrix[row].length) {
matrix[row][col] = number;
number++;
}

// we decrement col while incrementing row in order to traverse down and left
row++;
col--;
} while (row >= 0);
}

请注意,虽然此实现适用于所有矩阵大小(和形状),但它不会尽可能高效。其中nmatrix.length(假设是方阵),这个实现是大O中一个最优的O(n^2)类算法符号;然而,它有效地执行了 2*n^2 次迭代,而最佳解决方案只会执行 n^2

关于java - 二维数组对角填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25921902/

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