2016-07-15 105 views
1

我正在使用下面的代碼將NxN矩陣向左旋轉90度。但它有一些邏輯錯誤。大多數元素都是旋轉的,但有些還沒有。請幫我修改代碼。將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"); 

      } 
+0

你是什麼意思「旋轉90」? – bugwheels94

回答

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

謝謝。這是我想要的。 – TheHardRock

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