我有一个从右上角到左下角读取对角线值的java代码,但我希望代码从左上角到右下角读取值。
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
我想要像
这样的序列3 2 6 1 5 9 4 8 7
答案 0 :(得分:1)
int [][]mat = { {1,2,3},
{4,5,6},
{7,8,9},
};
int N=3;
for (int s=N-1; s>-N; --s) {
int iMin = s>0 ? s : 0;
int iMax = s>0 ? N : N+s;
for (int i=iMin; i<iMax; ++i) {
System.out.print(mat[i-s][i] + " ");
}
}
System.out.println();
<强>输出强>
3 2 6 1 5 9 4 8 7
答案 1 :(得分:0)
我修改了你的代码以实现所需的输出。
for (int s = N - 1; s > -1; s--) {
for (int i = s; i < N; i++) {
System.out.print(mat[i - s][i] + " ");
}
System.out.println();
}
for (int s = 1; s < N; s++) {
for (int i = s; i < N; i++) {
System.out.print(mat[i][i - s] + " ");
}
System.out.println();
}