首页 > 代码库 > Rotate Image

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?

思路:对于matrix[i][j],其顺时针旋转:1) 90度对应的点为matrix[j][n-1-i];  2) 180度对应的点为matrix[n-1-i][n-1-j];  3) 270度对应的点为matrix[n-1-j][i]。注意边界条件。

 1 class Solution { 2 public: 3     void rotate( vector<vector<int>> &matrix ) { 4         int n = matrix.size(); 5         for( int i = 0; i < n/2; ++i ) { 6             for( int j = i; j < n-i-1; ++j ) { 7                 int tmp = matrix[i][j]; 8                 matrix[i][j] = matrix[n-1-j][i]; 9                 matrix[n-1-j][i] = matrix[n-1-i][n-1-j];10                 matrix[n-1-i][n-1-j] = matrix[j][n-1-i];11                 matrix[j][n-1-i] = tmp;12             }13         }14         return;15     }16 };

 

Rotate Image