猿问

如何从左上角到右下角对角地迭代二维数组

我正在尝试为从左上角到右下角的所有对角线迭代一个方形二维数组。我有从左下角到右上角迭代的代码,但我需要调整它以另一种方式迭代。


public static void main(String[] args) {

       int[][] a = {

                {1,   2,  3,  4},

                {0,   1,  2,  3},

                {-1,  0,  1,  2},

                {-2, -1,  0,  1},

        };

        for (int j = 0; j <= a.length + a.length - 2; j++) {

            for (int k = 0; k <= j; k++) { // cols

                int l = j - k; //  rows

                if (l < a.length && k < a.length) {

                    System.out.print(a[l][k] + " ");

                }

            }

            System.out.println();

        }

}

结果是:


0 2 

-1 1 3 

-2 0 2 4 

-1 1 3 

0 2 

这是从左下角到右上角的对角线。如何调整该方法以另一种方式打印对角线以产生以下结果:


-2

-1 -1

0 0 0

1 1 1 1

2 2 2 

3 3

4

谢谢你的帮助。


守着一只汪
浏览 112回答 1
1回答

慕仙森

只需要镜像行地址public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp;int[][] a = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {1,&nbsp; &nbsp;2,&nbsp; 3,&nbsp; 4},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {0,&nbsp; &nbsp;1,&nbsp; 2,&nbsp; 3},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {-1,&nbsp; 0,&nbsp; 1,&nbsp; 2},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {-2, -1,&nbsp; 0,&nbsp; 1},&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j <= a.length + a.length - 2; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int k = 0; k <= j; k++) { // cols&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int l = j - k; //&nbsp; rows&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int mirror = a.lenght - l;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (mirror >= 0 && mirror < a.length && k < a.length) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(a[mirror][k] + " ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答