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?
原地圖像順時針旋轉90度。因為要求空間復雜度是常數,因此應該迭代旋轉操作。
class Solution { public: void rotate(vector> &matrix) { int n = matrix.size(); int layers = n/2;//圖像旋轉的圈數 for(int layer = 0;layer < layers;layer++)//每次循環一層,右青色到紫色 for(int i = layer;i
下面是網友給出的另一種方案:
class Solution { public: void rotate(vector> &matrix) { int i,j,temp; int n=matrix.size(); // 沿著副對角線反轉 for (int i = 0; i < n; ++i) { for (int j = 0; j < n - i; ++j) { temp = matrix[i][j]; matrix[i][j] = matrix[n - 1 - j][n - 1 - i]; matrix[n - 1 - j][n - 1 - i] = temp; } } // 沿著水平中線反轉 for (int i = 0; i < n / 2; ++i){ for (int j = 0; j < n; ++j) { temp = matrix[i][j]; matrix[i][j] = matrix[n - 1 - i][j]; matrix[n - 1 - i][j] = temp; } } } };