topic:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Analysis of the meaning:
The title of this problem is to rotate a matrix 90 degrees clockwise. At first glance, there is no idea, but if you analyze it carefully, you can find an algorithm with a complexity of O(n^2).
1. Transpose the matrix
2. Repeatedly swap the i-th and ni-th columns from i=1 to n/2 to get the correct result
A C++ implementation method is as follows:
#include<iostream> #include<vector> using namespace std; class Solution { public: void rotate(vector<vector<int> >& matrix) { int num = matrix[0].size(); vector<vector<int> > res; for(int i = 0; i < num; i++) { for(int j = 0; j < num; j++) { if(i == 0) { vector<int> temp; temp.push_back(matrix[i][j]); res.push_back(temp); } else { res[j].push_back(matrix[i][j]); } } } for(int i = 0; i < num/2; i++) { swapcol(i,num-i-1,res); } matrix = res; } void swapcol(int n1, int n2, vector<vector<int> > &res) { int num1 = res[0].size(); for(int i = 0; i < num1; i++) { swap(res[i][n1],res[i][n2]); } } void print(vector<vector<int> > &res) { int num = res[0].size(); for(int i = 0; i < num; i++) { for(int j = 0; j < num; j++) { if(j != num-1) { cout<<res[i][j]<<" "; } else { cout<<res[i][j]<<endl; } } } } };