给定一个n*n矩阵,对其顺时针旋转90度。
分析:将矩阵按圈(剥蒜)处理,对于矩阵A的(i, j)元素,旋转后的位置是(j, n - 1 - i)。
知道了旋转前后的对应关系,我们具体看下剥蒜法具体怎么来操作,对应行列我们操作多少步就可以终止,即循环的终止条件是什么。
先以3*3矩阵为例子,说明下过程
这样规律应该都能找到了。
//code
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
int row = matrix.size();//used as length.
int col = matrix[0].size() - 1;//used as index.
for (int i = 0; i < row / 2; ++i)
for (int j = i; j < col - i; ++j)
{
int tr = i, tc = j;
int tem = matrix[tr][tc];
for (int n = 0; n < 3; ++n)
{
int r = col - tc, c = tr;
matrix[tr][tc] = matrix[r][c];
tr = r; tc = c;
}
matrix[tr][tc] = tem;
}
}
};