【问题标题】:Logical Error in rotating a NxN matrix by 90 degree in place将 NxN 矩阵旋转 90 度的逻辑错误
【发布时间】:2016-07-15 10:16:08
【问题描述】:

我正在使用下面的代码将 NxN 矩阵向左旋转 90 度。但它有一些逻辑错误。大多数元素已经旋转,但有些还没有。请帮我更正代码。

            int n=4, x=1, i,j,temp;
            int a[][] = new int[n][n];

            for(i=0;i<n;i++){   
                for(j=0;j<n;j++){
                    a[i][j] = x++;
                }
            }

            for(i=0;i<n/2;i++){
                for(j=n-1;j>=n/2; j--){

                    temp = a[i][j];
                    a[i][j] = a[n-1-i][j];
                    a[n-1-i][j] = a[j][i];
                    a[j][i] = a[i][n-1-j];
                    a[i][n-1-j] = temp;
                }
            }


            for(i=0;i<n;i++){
                for(j=0;j<n;j++){
                    System.out.print(a[i][j]+" ");
                }
                System.out.print("\n");

            }

【问题讨论】:

  • “旋转90”是什么意思?

标签: java matrix logic


【解决方案1】:

我对您的程序进行了一些修改,现在它可以工作了。我提供了将矩阵向左和向右旋转 90 度的代码。看看吧。

for(i=0;i<n/2;i++){
    for(j=i; j<n-1-i ; j++){

        //Rotating left by 90 degrees
        temp = a[i][j];
        a[i][j] = a[j][n-1-i];
        a[j][n-1-i] = a[n-1-i][n-1-j];
        a[n-1-i][n-1-j] = a[n-1-j][i];
        a[n-1-j][i] = temp;

        /*  
        //Rotating right by 90 degrees
        temp = a[i][j];
        a[i][j] = a[n-1-j][i];
        a[n-1-j][i] = a[n-1-i][n-1-j];
        a[n-1-i][n-1-j] = a[j][n-1-i];
        a[j][n-1-i] = temp;
        */
    }
}

【讨论】:

  • 谢谢。这就是我想要的。
【解决方案2】:

您似乎在尝试使用来自this SO question 的代码,但它不起作用。我将答案逐字(AFAIK)转录成Java。我不知道你想旋转哪个方向,但也许这会对你有所帮助。

int n = 4;
int a[][] = new int[n][n];
int f = Math.floor((double)n/2);
int c = Math.ceil((double)n/2);

for (int x=0; x < f; ++x) {
    for (int y=0; y < c; ++y) {
        int temp = a[x,y];
        a[x, y] = a[y, n-1-x];
        a[y, n-1-x] = a[n-1-x, n-1-y];
        a[n-1-x, n-1-y] = a[n-1-y, x];
        a[n-1-y, x] = temp;
    }
}

【讨论】:

    【解决方案3】:

    另一种向左旋转 90 度的变体,这个解决方案只处理 int。它还关心奇数维度值。

    int dim = 5;
    int a[][] = new int[dim][dim];
    int floor = dim / 2;
    int ceil = (dim + 1) / 2;
    
    for (int row = 0; row < floor; row++) {
        for (int col = 0; col < ceil; col++) {
            int oppRow = dim - row - 1;
            int oppCol = dim - col - 1;
            int temp = a[row][col];
            a[row][col] = a[col][oppRow];
            a[col][oppRow] = a[oppRow][oppCol];
            a[oppRow][oppCol] = a[oppCol][row];
            a[oppCol][row] = temp;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-04
      • 2012-10-24
      • 2014-11-11
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 2013-05-05
      相关资源
      最近更新 更多