题目来源于网址:https://leetcode.com/
48. Rotate Image
- Total Accepted: 101913
- Total Submissions: 271175
- Difficulty: Medium
- Contributors: Admin
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?
Subscribe to see which companies asked this question.
分析:题目要求对一个n*n的二维矩阵顺时针旋转90度,于是根据旋转变换的规律和中心旋转的对称原则对每一行的数据进行变换。
代码如下:
void rotate(vector<vector<int>>& matrix) {
int dim=matrix.size();
int cnt = dim/2;
int tmp = 0;
int ss = dim;
for( int i=0; i<cnt; ++i) {
ss = dim -1 -2*i;
for( int j=i; j<ss+i; ++j) {
tmp = matrix[j][i];
matrix[j][i] = matrix[i+ss][j];
matrix[i+ss][j] = matrix[dim-j-1][i+ss];
matrix[dim-j-1][i+ss] = matrix[i][dim-j-1];
matrix[i][dim-j-1] = tmp;
}
}
}