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 int n = matrix.size(); 5 vector<vector<int> > tmp(n, vector<int>(n)); 6 for (int i = 0; i < n; ++i) { 7 for (int j = 0; j < n; ++j) { 8 tmp[i][j] = matrix[i][j]; 9 } 10 } 11 for (int i = 0; i < n; ++i) { 12 for (int j = 0; j < matrix[0].size(); ++j) { 13 matrix[j][n - 1 - i] = tmp[i][j]; 14 } 15 } 16 } 17 };
第二次刷leetcode发现好多题第一次做时就是A掉就不管了,其实还有很多东西可以继续挖掘,所以!要多刷几遍啊!原地转的话,这里用到一个小技巧,把一张纸上下折,再按对角线对折,那么它就转了90度了有木有,所以这里就用了这个技巧。
1 class Solution { 2 public: 3 void rotate(vector<vector<int> > &matrix) { 4 if (matrix.empty()) return; 5 int n = matrix.size(), tmp; 6 for (int i = 0; i < n/2; ++i) { 7 for (int j = 0; j < n; ++j) { 8 tmp = matrix[i][j]; 9 matrix[i][j] = matrix[n-1-i][j]; 10 matrix[n-1-i][j] = tmp; 11 } 12 } 13 for (int i = 0; i < n; ++i) { 14 for (int j = 0; j < i; ++j) { 15 tmp = matrix[i][j]; 16 matrix[i][j] = matrix[j][i]; 17 matrix[j][i] = tmp; 18 } 19 } 20 return; 21 } 22 };