对于 n*n矩阵旋转,取矩阵元素时从下标0开始,则(x,y)旋转后的位置为(y,n-1-x),在不考虑空间的情况下,可以遍历矩阵,根据旋转关系将元素填入新矩阵对应位置即可
伪代码为
for i = 0 to n -1
for j = 0 to n - 1
b[i][j] = a[j][n - 1 - i]
这种算法的空间复杂度为O(n*n)
另一种方法,空间复杂度为O(1)
假设n=4
最外层的旋转路线为:
(0,0)->(0,3)->(3,3)->(3,0)->(0,0)
(0,1)->(1,3)->(3,2)->(2,0)->(0,1)
(0,2)->(2,3)->(3,1)->(1,0)->(0,2)
次层旋转路线为:
(1,1)->(1,2)->(2,2)->(2, 1)->(1,1)
依此类推。
代码如下
#include <iostream>
#include <iomanip>
using namespace std;
void rotate(int** matrix, int matrixRowSize, int matrixColSize)
{
int n = matrixRowSize;
int m = n / 2;
for (int i = 0; i < m; i++) {
for (int j = i; j < n - 1 - i; j++) {
int startx = i, starty = j;
int x = startx, y = starty;
int newx = y, newy = n - 1 - x;
int tmp1 = *((int*)matrix + startx * matrixColSize + starty);
int tmp2;
while (newx != startx || newy != starty) {
tmp2 = *((int*)matrix + newx * matrixColSize + newy);
*((int*)matrix + newx * matrixColSize + newy) = tmp1;
x = newx, y = newy;
newx = y, newy = n - 1 - x;
tmp1 = tmp2;
}
*((int*)matrix + startx * matrixColSize + starty) = tmp1;
}
}
}
int main()
{
const int n = 2;
int matrix[n][n] = { { 1, 2}, { 3, 4} };
cout << "before rotate:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << right << setw(3) << matrix[i][j];
}
cout << endl;
}
rotate((int**)matrix, n, n);
cout << "after rotate:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << right << setw(3) << matrix[i][j];
}
cout << endl;
}
return 0;
}