2D阵列对角填充 [英] 2d array diagonally filling

查看:72
本文介绍了2D阵列对角填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1 2 3
4 5 6
7 8 9

这是我的常规数组,但是我需要像这样对角地放置它

this is my normal array, but i need to make it diagonally like this

1 2 4
3 5 7
6 8 9

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

this is very stupid way to make it work, but even it is not working because i am not able to find 2nd column elements.

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

推荐答案

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

Well, if you were to enumerate the indices in order for that fill pattern, you would get

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

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

So, you need to iterate through the total of the two indices. That is, the additive total. As you can see, 0,0 totals 0, 1,0 and 0,1 total 1, and so on. Giving us something like this:

0 1 2
1 2 3
2 3 4

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

To iterate in this diagonal pattern, we can do the following:

// 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.

Note that while this implementation will work for all matrix sizes (and shapes), it won't be as efficient as possible. Where n is matrix.length (assuming a square matrix), this implementation is an optimal O(n^2) class algorithm in big O notation; however, it effectively performs 2*n^2 iterations, whereas an optimal solution would only perform n^2.

这篇关于2D阵列对角填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆