我有一个制作 spirla 矩阵的代码,但我想写这个矩阵翻译。我的输出看起来像:
1 2 3
10 11 4
9 12 5
8 7 6
但这是错误的,因为我想要这样:
4 5 6
3 12 7
2 11 8
1 10 9
这是我的代码:
public void generateMatrixFile(int n , int m){
//n row, m column
int A[][]=new int[n][m];
int k=1, c1=0, c2=m-1, r1=0, r2=n-1;
while(k<=n*m) {
for(int i=c1;i<=c2;i++) {
A[r1][i]=k++;
}
for(int j=r1+1;j<=r2;j++) {
A[j][c2]=k++;
}
for(int i=c2-1;i>=c1;i--) {
A[r2][i]=k++;
}
for(int j=r2-1;j>=r1+1;j--) {
A[j][c1]=k++;
}
c1++;
c2--;
r1++;
r2--;
}
System.out.println("The Matrix is:");
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
}