那么,如果你要枚举这些填充模式的索引,你会得到
0,0
1,0
0,1
2,0
1,1
0,2
2,1
1,2
2,2
所以,你需要遍历两个指标的总和。也就是说,总添加量。如您所见,0,0总计0,1,0和0,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);
}
请注意,虽然此实现将适用于所有矩阵大小(和形状),但它不会尽可能高效。其中n是matrix.length(假设为方形矩阵),该实现是大O符号中的最优O(n ^ 2)类算法;然而,它有效地执行2×n ^ 2次迭代,而最优解只能执行n ^ 2。