2016-07-15 84 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; 
    } 
}