gpt4 book ai didi

java - 如何在 ZigZag 路径中​​遍历和打印二维数组

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:12 25 4
gpt4 key购买 nike

假设我有一个数组

A[][] = {{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9,10,11,12}};

然后我想打印一个wave,这样输出就出来了

{1,5,9,10,6,2,3,7,11,12,8,4}

我该怎么做?

这是我的代码,但它给了我 ArrayIndexOutOfBound

public class Wave1 {

public static void main(String[] args) {
// TODO Auto-generated method stub
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16},{17,18,19,20}} ;
System.out.println("Row "+a.length);
for(int i=0;i<a.length;i++){
System.out.println("Column "+i+"th "+a[i].length);
}
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
System.out.print(a[i][j]+" ");
}
}
System.out.println();
for(int i=0;i<a.length+1;i++){
if(i%2==0){
for(int j=0;j<a.length;j++){
System.out.print(a[j][i]+" ");
}
}
else{
for(int j=a.length-1;j>=0;j--){
System.out.print(a[j][i]+" ");

}
}
}

提前致谢

最佳答案

您似乎想要打印矩阵的每一列,其中偶数索引列按升序打印,奇数索引列按降序打印。

for (int col = 0; col < a[0].length; col++) {
if (col % 2 == 0) {
for (int row = 0; row < a.length; row++)
System.out.print(a[row][col] + " ");
System.out.println();
} else {
for (int row = a.length - 1; row >= 0; row--)
System.out.print(a[row][col] + " ");
System.out.println();
}
}

输出:

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

关于java - 如何在 ZigZag 路径中​​遍历和打印二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35971447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com