0

我有一个制作 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();
        }
    }
4

2 回答 2

1

解决此问题的方法如下:

  • 更改矩阵的填充方式,或
  • 更改矩阵的打印方式,或
  • 将上述两种方法结合起来。

由于您想要的输出是平移矩阵和翻转其维度的组合,因此您需要一种组合方法:切换nm,并反转第一个循环的迭代顺序以获得所需的输出。您还需要修改嵌套循环以在k到达n*m标记时停止。

public static void generateMatrixFile(int n , int m) {
    int A[][] = new int[m][n]; // Switched m and n
    int k=1, c1=0, c2=n-1, r1=0, r2=m-1; // Switched m and n
    while (k<=n*m) {
        for (int i=c1;i<=c2 && k<=n*m;i++) {
            A[r1][i]=k++;
        }
        for(int j=r1+1;j<=r2 && k<=n*m;j++) {
            A[j][c2]=k++;
        }
        for(int i=c2-1;i>=c1 && k<=n*m;i--) {
            A[r2][i]=k++;
        }
        for(int j=r2-1;j>=r1+1 && k<=n*m;j--) {
            A[j][c1]=k++;
        }
        c1++;
        c2--;
        r1++;
        r2--;
    }
    System.out.println("The Matrix is:");
    for (int i=n-1;i>=0;i--) {
        for(int j=0 ; j < m ; j++) {
            System.out.print(A[j][i]+ "\t");
        }
        System.out.println();
    }
}

演示。

于 2015-12-29T14:07:11.950 回答
0

您只需要更改循环的顺序,并据此调整变量。

    public static 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 j=r2;j>=r1;j--)
            {
                A[j][c1]=k++;
            }
            for(int i=c1+1;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+1;i--)
            {
                A[r2][i]=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();
        }
}

希望有帮助。

于 2015-12-29T14:17:55.450 回答