【LeetCode】48. Rotate Image
介绍
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
题意:让n×n的矩阵顺时针旋转90都,考虑如果原地旋转需要怎么办?
解答:
如下是一个矩阵顺时针旋转后的例子。
如果采用一个新的矩阵作为中间变量,很容易就能够写出来代码。
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
vector<int> row(n);
vector<vector<int>> res(n,row);
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
res[j][n-1-i] = matrix[i][j];
}
}
matrix = res;
}
};
考虑原地旋转,不申请其他额外空间。这里采用LeetCode上的高票答案。这个答案非常有意思:
/*
* 顺时针旋转
* 首先将矩阵按照上下行进行上下反转,然后按照对角线进行交换元素。最后得到结果。
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
int up = 0,down = n-1;
while(up < down)
{
for(int i = 0; i < n; ++i)
{
swap(matrix[up][i],matrix[down][i]);
}
++up,--down;
}
for(int i = 0; i < n; ++i)
{
for(int j = i+1; j < n; j++)
{
swap(matrix[i][j],matrix[j][i]);
}
}
}
};