如:
[
[1,2,3],
[4,5,6],
[7,8,9],
]
打印结果 1 2 4 7 5 3 6 8 9
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int M = in.nextInt();
int[][] input = new int[M][M];
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
input[i][j] = in.nextInt();
}
}
int count = 0;//一共需要循环的次数
while (count < 2 * M - 1) {
int i, j;
i = count / (M - 1) == 0 ? count : M - 1;//若是没有超过行索引,就是行索引,超过还是行索引
j = count / (M - 1) == 0 ? 0 : count - (M - 1);//若是超过行索引,那么j+超过部分
if (count % 2 == 0) {//第偶数次打印 i-- j++
while (0 <= i && i < M && 0 <= j && j < M) {
System.out.print(input[i--][j++] + "\t");
}
} else {//第奇数次打印
while (0 <= i && i < M && 0 <= j && j < M) {
System.out.print(input[j++][i--] + "\t");
}
}
count++;
}
}