题目:
将一个n*n的矩阵顺时针旋转90度
思路有两种:假设n=5
第一种,我们可以看看每一个位置的元素原始位置和最终位置的坐标,寻找规律
像这样:(0,0)->(0,4);(0,1)->(1,4);(1,0)->(0,3);(1,1)->(1,3);所以我们可以得到如下规律:原来的列号变成了新位置的行号;原来的行号假设为row,变为n-1-row;
这种算法时间复杂度为O(n^2),空间复杂度也为O(n^2);代码这里就不写了,有兴趣的可以自己试试;
第二种,这种也是笔者一开始没有想到的,是在面试官提示下才总结出来的。
我们可以分层处理,观察元素位置的持续变化,像这样:
第一层: :
(0,0)->(0,4)->(4,4)->(4,0)->(0,0);
(0,1)->(1.4)->(4,3)->(3,0)->(0,1);
(0,2)->(2.4)->(4,2)->(2,0)->(0,2);
(0,3)->(3.4)->(4,1)->(1,0)->(0,3);
(0,4)->(4.4)->(4,0)->(0,0)->(0,4); //same as first line
第二层:
(1,1)->(1.3)->(3,3)->(3,1)->(1,1);
(1,2)->(2.3)->(3,2)->(2,1)->(1,2);
(1,3)->(3.3)->(3,1)->(1,1)->(1,3);
所以我们只需要一个临时变量,就可以实现这种旋转,具体代码如下,仅供参考,欢迎拍砖:
#include <iostream>
#include <vector>
/*
Program:
rotate a n*n matrix by 90 degree clockwise
tips:
suppose n=5;
first way: (0,0)->(0,4);(0,1)->(1,4);(1,0)->(0,3);(1,1)->(1,3);
so we can conclude like this: original column changed to row,
original row changed to n-1-row
time complexity:O(n^2); space complexity:O(n^2);
second way: obviously we should handle this problem by deck, supposing the deck counts from outer to inner,
numbered from 0;
first deck:
(0,0)->(0,4)->(4,4)->(4,0)->(0,0);
(0,1)->(1.4)->(4,3)->(3,0)->(0,1);
(0,2)->(2.4)->(4,2)->(2,0)->(0,2);
(0,3)->(3.4)->(4,1)->(1,0)->(0,3);
(0,4)->(4.4)->(4,0)->(0,0)->(0,4); //same as first line
second deck:
(1,1)->(1.3)->(3,3)->(3,1)->(1,1);
(1,2)->(2.3)->(3,2)->(2,1)->(1,2);
(1,3)->(3.3)->(3,1)->(1,1)->(1,3);
time complexity:O(n^2); space complexity:O(1);
*/
using namespace std;
void rotateMatrix(vector<vector<int> > &matrix);
void printMatrix(vector<vector<int> > &matrix);
int main()
{
vector<vector<int> > matrix;
for(int i=0;i<5;++i)
{
vector<int> temp;
for(int j=0;j<5;++j)
{
temp.push_back(5*i+j+1);
}
matrix.push_back(temp);
}
cout<<"The original matrix is like: "<<endl;
printMatrix(matrix);
rotateMatrix(matrix);
cout<<"Now the matrix changed like this: "<<endl;
printMatrix(matrix);
return 0;
}
void rotateMatrix(vector<vector<int> > &matrix)
{
int n=matrix.size();
/*handle the matrix by deck*/
for(int deck=0;deck<n/2;++deck)
{
for(int i=0;i<n-2*deck-1;++i)
{
int temp(0);
temp=matrix[deck][i+deck];
matrix[deck][i+deck]=matrix[n-1-i-deck][deck];
matrix[n-1-i-deck][deck]=matrix[n-1-deck][n-1-i-deck];
matrix[n-1-deck][n-1-i-deck]=matrix[i+deck][n-1-deck];
matrix[i+deck][n-1-deck]=temp;
}
}
}
void printMatrix(vector<vector<int> > &matrix)
{
for(int i=0;i<5;++i)
{
for(int j=0;j<5;++j)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}