简体   繁体   中英

Traversing a 2D array matrix diagonally from bottom left to upper right

I have a 3x4 matrix represented by a 2D array:

. 0  1  2  3
0 a  c  f  i   
1 b  e  h  k
2 d  g  j  l

and my approach to traverse the diagonal slice was to treat each slice as a sum, like this:

a = (0+0) = 0
b,c = (0+1),(1+0) = 1
d,e,f = (0+2),(1+1),(2+0) = 2
g,h,i = (1+2),(2+1),(3+0) = 3
j, k = (2+2),(3+1) = 4
l = (3+2) = 5

However, my code right now prints it in the opposite way that I want it to, which is from upper right to bottom left.

Current Output is:

acbfedihgkjl

Desired Output is:

abcdefghijkl

        for (int sum = 0; sum <= numRows + numColumns - 2; sum++) {
            for (int i = 0; i < numRows; i++) {
                int j = sum - i;

                if ((i >= 0 && i < numRows) && (j >= 0 && j < numColumns)) {
                    System.out.print(array[i][j]);
                }
            }
        }

Can somebody point me in the right direction on how to fix my code to get the output that I want?

int i = 0;
int j = 0;
int n = 0;
int x = 3;
int y = 4;
int newSize = Math.max(x,y) * Math.max(x,y);

while(n < newSize){
    if(i <= x && j <= y)
        System.out.println(array[i][j]);
    n++;
    if(i == 0) {
        i = n:
        j = 0;
    } else {
        --i;
        ++j;
    }
}

While it isn't very pretty, I think this will do it:

int i = 0;
int j = 0;
while (true) {
    System.out.println("" + array[i][j]);
    --i;
    ++j;
    if (i < 0) {
        if (j == numCols)
            break;
        i = Math.min(j, numRows - 1);
        j = Math.max(j - numCols + 2, 0); 
    } else if (j >= numCols) {
        if (i == numRows - 2)
            break;
        i = numRows - 1;
        j = Math.max(j + 2 - numCols + i, 0);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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