将NxN矩阵旋转90度的逻辑错误

时间:2016-07-15 10:16:08

标签: java matrix logic

我使用下面的代码将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");

            }

3 个答案:

答案 0 :(得分: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;
        */
    }
}

答案 1 :(得分:0)

看起来您正在尝试使用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;
    }
}

答案 2 :(得分:0)

左边旋转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;
    }
}