沿对角线遍历二维数组

23
我写了下面的代码来遍历一个数组的一半对角线:
String[][] b = [a,b,c]
               [d,e,f]
               [g,h,i];  

public void LoopDiag()
   for (int i = b.length - 1; i > 0; i--) {
       String temp = "";
       for (int j = 0, x = i; x <= b.length - 1; j++, x++) {
          temp = temp+b[x][j];
       }
       System.out.println(temp)
   }


   for (int i = 0; i <= b.length - 1; i++) {
        String temp = "";
        for (int j = 0, y = i; y <= b.length - 1; j++, y++) {
        temp = temp+b[j][y];
        }
        System.out.println(temp);
   }
}

现在它打印出对角线,即当前输出:

g dh aei bf c

我应该如何使其打印另一半的对角线,即所需输出:

a db gec hf i 

请将输出格式化,以便我们能够看到。 - Ruchira Gayan Ranaweera
1
你有尝试自己解决这个问题吗?你遇到了什么具体困难?这是你的作业吗? - Andrey
12个回答

1

这是如何实现的:

int [][]mat = { {1,2,3},
                {4,5,6},
                {7,8,9},
};

int N=3;

for (int s=0; s<N; s++) {
    for (int i=s; i>-1; i--) {
        System.out.print(mat[i][s-i] + " ");
    }
    System.out.println();
}

for (int s=1; s<N; s++) {
    for (int i=N-1; i>=s; i--) {
        System.out.print(mat[i][s+N-1-i] + " ");
    }
    System.out.println();
}

第一个循环从第一列开始打印对角线,第二个循环打印剩余的对角线(从底部行开始)。
输出:
1 
4 2 
7 5 3 
8 6 
9 

-1

这与leoflower在此处发布的内容相同。我只是更改了变量名称以便更好地理解。

level = 表示正在打印的对角线的当前级别。例如:level = 2表示具有索引(0,2),(1,1),(2,0)的对角线元素

currDiagRowIndex = 表示正在打印的当前对角线的行索引

currDiagColIndex = 表示正在打印的当前对角线的列索引

void printMatrixDiagonal(int matrix[][], int endRowIndex, int endColIndex){
    for(int level = 0; level < endColIndex; level++){
        for(int currDiagRowIndex = 0, currDiagColIndex = level; currDiagRowIndex < endRowIndex && currDiagColIndex >= 0 ; currDiagRowIndex++, currDiagColIndex--){
            System.out.print(matrix[currDiagRowIndex][currDiagColIndex] + "  ");
        }
        System.out.println();
    }

    for(int level = 1; level < endRowIndex; level++){
        for(int currDiagRowIndex = level, currDiagColIndex = endColIndex-1; currDiagRowIndex < endRowIndex && currDiagColIndex >= 0; currDiagRowIndex++, currDiagColIndex--){
            System.out.print(matrix[currDiagRowIndex][currDiagColIndex]+ "  ");
        }
        System.out.println();
    }
}

输入:

1 2 3 4 5 
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

输出:

1  
2  6  
3  7  11  
4  8  12  16  
5  9  13  17  21  
10  14  18  22  
15  19  23  
20  24  
25  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接