题目描述:(链接)
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?
解题思路:
先将矩阵选择180度,然后再将矩阵上下折叠。
1 class Solution { 2 public: 3 void rotate(vector<vector<int> > &matrix) { 4 int temp; 5 int len = matrix.size(); 6 7 // 现将矩阵旋转180° 8 for(int i = 0; i < len ; ++i){ 9 for(int j = 0; j < len; ++j){ 10 if(i + j <= len - 1){ 11 temp = matrix[i][j]; 12 matrix[i][j] = matrix[len - j - 1][len - i - 1]; 13 matrix[len - j - 1][len - i - 1] = temp; 14 } 15 } 16 } 17 18 // 将矩阵上下反转 19 for(int i = 0; i < len / 2; ++i){ 20 for(int j = 0; j < len; ++j){ 21 temp = matrix[i][j]; 22 matrix[i][j] = matrix[len - 1 - i][j]; 23 matrix[len - 1 - i][j] = temp; 24 } 25 } 26 27 } 28 };