gpt4 book ai didi

java - 以螺旋顺序打印二维数组

转载 作者:行者123 更新时间:2023-11-29 03:52:59 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Pattern consisting of numbers moving in clockwise direction around a rectangular shape (length and breadth decreasing each time)

如何使用 JAVA 以螺旋顺序打印二维数组?请帮忙,我不知道。

示例数组:

1  2  3  4

5 6 7 8

9 10 11 12

13 14 15 16

输出:

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

这是我尝试过的:

public static void main(String[] args) {

    int[][] values = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};

for (int i = (values.length * values[0].length)-1, j = 0; i > 0; i--, j++) {
for (int k = j; k < i; k++) {
System.out.print(values[j][k]);
}

for (int k = j; k < i; k++) {
System.out.print(values[k][i]);
}

for (int k = i; k > j; k--) {
System.out.print(values[i][k]);
}

for (int k = i; k > j; k--) {
System.out.print(values[k][j]);
}
}

}

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