題目:
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?
解答:
一開始想的很復雜,希望找到一個通式應對所有角度的旋轉。所有的細節寫在《【圖像處理】基於OpenCV底層實現的圖片旋轉》。
其實沒有必要,因為90度是非常特殊的一種旋轉,可以直觀上賦值:
class Solution { public: void rotate(vector>& matrix) { int m = matrix.size(); int n = matrix[0].size(); vector tmp(m, 0); vector > ans(n, tmp); for(int i=0; i
但仔細看題目要求:in-place(原地)。想了半天沒想出來原地旋轉的方法。直到看到巧妙做法:傳送門。精粹就在下圖中:
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; } } } };