LeetCode:Rotate Image
Problem:
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?
思路:顺时针方向:首先沿着副对角线反转一次,再沿着水平中线反转一次。
逆时针方向:首先沿着主对角线反转一次,再沿着水平中线反转一次。
1 class Solution { 2 public: 3 void rotate(vector<vector<int>>& matrix) { 4 5 const int n=matrix.size(); 6 7 //沿着副对角线的反转 8 for(int i=0;i<n;i++) 9 for(int j=0;j<n-i;j++) 10 swap(matrix[i][j],matrix[n-1-j][n-1-i]); 11 12 //沿着水平中线反转
14 for(int i=0;i<n/2;i++) 15 for(int j=0;j<n;j++) 16 swap(matrix[i][j],matrix[n-1-i][j]); 17 18 } 19 };