可能重複:
Pattern consisting of numbers moving in clockwise direction around a rectangular shape (length and breadth decreasing each time)打印2- d陣列
如何打印在螺旋的次序使用JAVA 2維陣列?請幫忙,我沒有任何想法。
樣本陣列:
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
這裏是我嘗試:
公共靜態無效的主要(字串[] 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]);
}
}
}
相關:http://stackoverflow.com/questions/7042165/pattern-consisting-of-numbers-moving順時針方向 - 長方形 –
這是作業嗎?你試過什麼了? –