[LeetCode] 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?
需要O(N)的辅助空间,应该有个O(1)空间的。但似乎比较复杂。
1 class Solution { 2 public: 3 void rotate(vector<vector<int> > &matrix) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<int> temp(matrix.size()); 7 8 int begX = 0; 9 int begY = 0; 10 int endX = matrix.size() - 1; 11 int endY = matrix[0].size() - 1; 12 13 while(begX < endX) 14 { 15 for(int i = begY + 1; i <= endY - 1; i++) 16 temp[i] = matrix[begX][i]; 17 18 int index = endX - 1; 19 for(int i = begY + 1; i <= endY - 1; i++) 20 matrix[begX][i] = matrix[index--][begY]; 21 22 index = begY + 1; 23 for(int i = begX + 1; i <= endX - 1; i++) 24 matrix[i][begY] = matrix[endX][index++]; 25 26 index = endX - 1; 27 for(int i = begY + 1; i <= endY - 1; i++) 28 matrix[endX][i] = matrix[index--][endY]; 29 30 for(int i = begX + 1; i <= endX - 1; i++) 31 matrix[i][endY] = temp[i]; 32 33 int t = matrix[begX][begY]; 34 35 matrix[begX][begY] = matrix[endX][begY]; 36 matrix[endX][begY] = matrix[endX][endY]; 37 matrix[endX][endY] = matrix[begX][endY]; 38 matrix[begX][endY] = t; 39 40 begX++; 41 begY++; 42 endX--; 43 endY--; 44 } 45 } 46 };