簡體   English   中英

將 NxN 矩陣原位旋轉 90 度的邏輯錯誤

[英]Logical Error in rotating a NxN matrix by 90 degree in place

我正在使用下面的代碼將 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 度的代碼。 看一看。

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;
        */
    }
}

看起來您好像在嘗試使用此 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;
    }
}

向左旋轉 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM