题目链接:https://leetcode.com/problems/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?
思路:如果允许额外的内存的话,就比较简单了,把第一行放到最后一列,第二行放到倒数第二列,第三行放到倒数第三列,依次类推。
代码如下:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int len = matrix.size();
if(len == 0) return;
vector<int> tem(len,0);
vector<vector<int>> result(len, tem);
for(int i = 0; i< len; i++)
for(int j =0; j< len; j++)
result[j][len-i-1] = matrix[i][j];
matrix = result;
}
};
而事实上如果要求不能使用额外的内存的话就变的有点麻烦了,观察发现元素的位置变化形成了一个环形,想了好久没想通怎么做,看了一下别人怎么做的,发现是做两次变换。
第一次是逆对角线翻转,然后在上下翻转一下就可以实现。盗个图:
代码如下:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
if(matrix.size() ==0) return;
int row = matrix.size(), col = matrix[0].size();
for(int i = 0; i < row; i++)
for(int j = 0; j < col-i; j++)
swap(matrix[i][j], matrix[row-j-1][col-i-1]);
for(int i = 0; i < row/2; i++) swap(matrix[i], matrix[row-i-1]);
}
};