You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
基本思路为:
从最外圈到最内圈进行遍历交换,需要的圈数为
n2
,在每圈元素的交换过程中,对于任意坐标数据(i,j),交换路径依次为(i,j) –> (j, n-i-1) –> (n-i-1, n-j-1) –> (n-j-1, i),每圈要进行的赋值的次数依次为5(n-1), 5(n-3), 5(n-5), … ,5次,因此时间复杂度为O(
n2
),由于每次交换实际只需要一个临时变量data保存当前数据,其他索引值仅仅只是为了程序的可读性进行设置,因此空间复杂度为O(1)。
class Solution {
public:
void rotate_swap_four_data(vector<vector<int>>& matrix, int row, int col)
{
int order = matrix.size();
int top_left_row = row;
int top_left_col = col;
int top_right_row = col;
int top_right_col = order - row - 1;
int bottom_right_row = order - row - 1;
int bottom_right_col = order - col - 1;
int bottom_left_row = order - col - 1;
int bottom_left_col = row;
int data = matrix[top_left_row][top_left_col];
matrix[top_left_row][top_left_col] = matrix[bottom_left_row][bottom_left_col];
matrix[bottom_left_row][bottom_left_col] = matrix[bottom_right_row][bottom_right_col];
matrix[bottom_right_row][bottom_right_col] = matrix[top_right_row][top_right_col];
matrix[top_right_row][top_right_col] = data;
}
void rotate(vector<vector<int>>& matrix) {
int matrix_order = matrix.size();
int round_count = matrix_order/2;
for(int round = 0; round < round_count; round++)
{
int start_pos = round;
int end_pos = matrix_order - round - 1;
for(int col = start_pos; col < end_pos; col++)
{
rotate_swap_four_data(matrix, start_pos, col);
}
}
}
};