48. Rotate Image
- Total Accepted: 96625
- Total Submissions: 259249
- Difficulty: Medium
- Contributors: Admin
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?
Solution 1:
對於90度的翻轉有很多方法,一步或多步都可以解,我們先來看一種直接的方法,對於當前位置,計算旋轉后的新位置,然后再計算下一個新位置,第四個位置又變成當前位置了,所以這個方法每次循環換四個數字,如下所示:
1 2 3 7 2 1 7 4 1
4 5 6 --> 4 5 6 --> 8 5 2
7 8 9 9 8 3 9 6 3
1 class Solution { 2 public: 3 void rotate(vector<vector<int>>& matrix) { 4 int n = matrix.size(); 5 for(int i = 0; i < n / 2; i++){ 6 for(int j = i; j < n - 1 - i; j++){ 7 int tmp = matrix[i][j]; 8 matrix[i][j] = matrix[n - 1 - j][i]; 9 matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]; 10 matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]; 11 matrix[j][n - 1 - i] = tmp; 12 } 13 } 14 } 15 };
Solution 2:
還有一種解法,首先以從對角線為軸翻轉,然后再以x軸中線上下翻轉即可得到結果,如下圖所示(其中藍色數字表示翻轉軸):
1 2 3 9 6 3 7 4 1
4 5 6 --> 8 5 2 --> 8 5 2
7 8 9 7 4 1 9 6 3
1 class Solution { 2 public: 3 void rotate(vector<vector<int>>& matrix) { 4 int n = matrix.size(); 5 for(int i = 0; i < n - 1; i++){//i只能取到 n - 2, 因為n - 1是對稱軸 6 for(int j = 0; j < n - 1 - i; j++){//j只能取到n - 1 - i, 在對稱軸的左邊 7 swap(matrix[i][j], matrix[n - 1 - j][n - 1 - i]); 8 } 9 } 10 for(int i = 0; i < n / 2; i++){//i只能取到橫向中間軸的上面 11 for(int j = 0; j < n; j++){//j可以取到所有值 12 swap(matrix[i][j], matrix[n - 1 - i][j]);//按橫向軸翻轉,j不變;i變為n-1-i 13 } 14 } 15 } 16 };
Solution 3:
最后再來看一種方法,這種方法首先對原數組取其轉置矩陣,然后把每行的數字翻轉可得到結果,如下所示(其中藍色數字表示翻轉軸):
1 2 3 1 4 7 7 4 1
4 5 6 --> 2 5 8 --> 8 5 2
7 8 9 3 6 9 9 6 3
1 class Solution { 2 public: 3 void rotate(vector<vector<int>>& matrix) { 4 int n = matrix.size(); 5 for(int i = 0; i < n; i++){ 6 for(int j = i + 1; j < n; j++){//j取i - 1, 因為對稱軸是(i,i) 7 swap(matrix[i][j], matrix[j][i]); 8 } 9 reverse(matrix[i].begin(), matrix[i].end());//按豎向中軸線翻轉 直接按行reverse即可 10 } 11 } 12 };