题目
给定一个 n × n n × n n×n 的二维矩阵 m a t r i x matrix matrix 表示一个图像。请你将图像顺时针旋转 90 90 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
思路
- 原来 ( i , j ) (i,j) (i,j) 位置的数旋转后到 ( j , n − 1 − i ) (j, n-1-i) (j,n−1−i)
- 只需对左上角的元素进行操作
代码
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
int row_ind;
int col_ind;
if(n%2 == 0){
col_ind = n/2-1;
row_ind = n/2-1;
}
else{
col_ind = (n-1)/2;
row_ind = (n-1)/2-1;
}
for(int i = 0; i <= row_ind; i++){
for(int j = 0; j <= col_ind; j++){
int temp_i = i, temp_j = j;
int temp, temp_last = matrix[i][j];
for(int k = 0; k < 4; k++){
temp = matrix[temp_j][n-1-temp_i];
matrix[temp_j][n-1-temp_i] = temp_last;
temp_last = temp;
int temp_temp_j = temp_j;
temp_j = n-1-temp_i;
temp_i = temp_temp_j;
}
}
}
}
};