如何旋转matrix90度,而不使用任何额外的空间?

可能重复:
将图像旋转90度的algorithm? (没有额外的记忆)

说90度我的意思是说如果:

A = {1,2,3, 4,5,6, 7,8,9} 

然后在90度旋转A后变成:

 A = {7,4,1, 8,5,2, 9,6,3} 

a基于nxn数组0的索引

 f = floor(n/2) c = ceil(n/2) for x = 0 to f - 1 for y = 0 to c - 1 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 

编辑如果你想避免使用温度,这个工程(它也是在正确的方向旋转)这一次在Python中。

 def rot2(a): n = len(a) c = (n+1) / 2 f = n / 2 for x in range(c): for y in range(f): a[x][y] = a[x][y] ^ a[n-1-y][x] a[n-1-y][x] = a[x][y] ^ a[n-1-y][x] a[x][y] = a[x][y] ^ a[n-1-y][x] a[n-1-y][x] = a[n-1-y][x] ^ a[n-1-x][n-1-y] a[n-1-x][n-1-y] = a[n-1-y][x] ^ a[n-1-x][n-1-y] a[n-1-y][x] = a[n-1-y][x] ^ a[n-1-x][n-1-y] a[n-1-x][n-1-y] = a[n-1-x][n-1-y]^a[y][n-1-x] a[y][n-1-x] = a[n-1-x][n-1-y]^a[y][n-1-x] a[n-1-x][n-1-y] = a[n-1-x][n-1-y]^a[y][n-1-x] 

注意:这只适用于整数matrix。

转置和交换行或列(取决于你想要向左还是向右旋转)。

例如

 1) original matrix 1 2 3 4 5 6 7 8 9 2) transpose 1 4 7 2 5 8 3 6 9 3-a) change rows to rotate left 3 6 9 2 5 8 1 4 7 3-b) or change columns to rotate right 7 4 1 8 5 2 9 6 3 

所有这些操作都可以在不分配内存的情况下完成。

该algorithm是旋转每个“环”,从最外层到最内层。

 AAAAA ABBBA ABCBA ABBBA AAAAA 

algorithm会先旋转所有的A,然后B旋转C。 旋转一个戒指需要一次移动4个值。

索引i的范围是0..ring-width-1,例如对于A,宽度是5。

  (i,0) -> temp (0, Ni-1) -> (i, 0) (Ni-1, N-1) -> (0, Ni-1) (N-1, i) -> (Ni-1, N-1) temp -> (N-1, i) 

然后对于每个连续的内环重复这个过程,偏移使环宽度减less2的坐标。

[代码中出现了另一个答案,所以我不会再重复。]

使用上面的@Narek描述的方法在C中完成实现

 #include <stdio.h> int n; unsigned int arr[100][100]; void rotate() { int i,j,temp; for(i=0; i<n; i++) { for(j=i; j<n; j++) { if(i!=j) { arr[i][j]^=arr[j][i]; arr[j][i]^=arr[i][j]; arr[i][j]^=arr[j][i]; } } } for(i=0; i<n/2; i++) { for(j=0; j<n; j++) { arr[j][i]^=arr[j][n-1-i]; arr[j][n-1-i]^=arr[j][i]; arr[j][i]^=arr[j][n-1-i]; } } } void display(){ int i,j; for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("%d",arr[i][j]);} printf("%s","\n"); } } int main(int argc, char *argv[]){ int i,j; printf("%s","Enter size of matrix:"); scanf("%d",&n); printf("%s","Enter matrix elements\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { scanf("%d",&arr[i][j]); } } rotate(); display(); return 0; } 

看到这篇文章就地matrix转置; 也是谷歌的“就地matrix换位”。 它可以很容易地适应旋转90度。 为了转置matrixmatrix,只需将b[i][j]b[j][i]交换,其中b[k][l]a[n*k+l] 。 在非矩形matrix上,这是相当困难的。 “没有任何额外的空间”是一个相当强大的要求,也许你的意思是O(1)空间? (假设整数是固定的大小)在C ++实现: 这里 。

你需要一个临时variables,那么它只是跳转元素。

 temp = A[0]; A[0] = A[6]; A[6] = A[8]; A[8] = A[2]; A[2] = temp; temp = A[1]; A[1] = A[3]; A[3] = A[7]; A[7] = A[5]; A[5] = temp; 

我遇到了以下的实现:

对于方matrix:

 for n = 0 to N - 2 for m = n + 1 to N - 1 swap A(n,m) with A(m,n) 

对于矩形matrix:

 for each length>1 cycle C of the permutation pick a starting address s in C let D = data at s let x = predecessor of s in the cycle while x ≠ s move data from x to successor of x let x = predecessor of x move data from D to successor of s 

欲了解更多信息,可以在这里参考: http : //en.wikipedia.org/wiki/In-place_matrix_transposition