简体   繁体   English

对角遍历二维数组

[英]Iterating diagonally through a 2d array

I have to iterate through an 2D array of chars.我必须遍历一个二维字符数组。 I already have the code to iterate / but I'm lost when it comes to .我已经有了要迭代的代码 / 但是当涉及到 .

Here is my 2d array:这是我的二维数组:

a,v,i,o,n,l
t,o,t,o,l,l
m,a,r,c,o,e
s,a,g,r,c,i
o,e,n,z,o,g
s,t,r,a,r,u

I already have:我已经有:

a
tv
moi
....

and I need:我需要:

l
nl
ole
....

Here is the code to iterate / :这是迭代 / 的代码:

int size = 6;

for (int k = 0 ; k < size ; k++) {
    for (int j = 0 ; j <= k ; j++) {
        int i = k - j;
        System.out.print( lista[i][j] + " " );
    }
    System.out.println();
}

for (int k = size - 2 ; k >= 0 ; k--) {
    for (int j = 0 ; j <= k ; j++) {
        int i = k - j;
        System.out.print(lista[size - j - 1][size - i - 1] + " " );
    }
    System.out.println();
}

Try this:试试这个:

public class Matrix {
    public static void main(String[] args) {
        char[][] arr = {
                { 'a', 'v', 'i', 'o', 'n', 'l' }, 
                { 't', 'o', 't', 'o', 'l', 'l' },
                { 'm', 'a', 'r', 'c', 'o', 'e' }, 
                { 's', 'a', 'g', 'r', 'c', 'i' }, 
                { 'o', 'e', 'n', 'z', 'o', 'g' },
                { 's', 't', 'r', 'a', 'r', 'u' } };
        for (int n = -arr.length; n <= arr.length; n++) {
            for(int i = 0; i < arr.length; i++){
                if((i-n>=0)&&(i-n<arr.length)){
                    System.out.print(arr[i][i-n]);
                }
            }
            System.out.println();
        }
    }
}

You can use your own code.您可以使用自己的代码。 The only thing you need to do is transpose your matrix first.您唯一需要做的就是先转置矩阵。 I have written and tested it for you.我已经为你编写并测试了它。 myArray is the array you gave us as input and yourArray is the one you need to use in for your code as lista. myArray 是您作为输入提供给我们的数组,而 yourArray 是您需要在代码中用作 lista 的数组。

for (int i = 5; i >= 0; i--) {
    for (int j = 0; j <= 5; j++) {
       yourArray[5 - i][j] = myArray[j][i];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM