[LeetCode] 48. Rotate Image

</br>


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?


</br>

Solution

Common way to rotate a image is to follow the step mentioned below.

Clockwise Rotate
  1 2 3     7 8 9     7 4 1
  4 5 6  => 4 5 6  => 8 5 2
  7 8 9     1 2 3     9 6 3

first reverse up to down, then swap the symmetry 
Anti-clockwise Rotate
  1 2 3     3 2 1     3 6 9
  4 5 6  => 6 5 4  => 2 5 8
  7 8 9     9 8 7     1 4 7

first reverse left to right, then swap the symmetry

Therefore, in order to perform image rotation, we do not need to store matrix in additional space; instead, we can achieve this in-place by following steps above. First, perform reverse the matrix; then, swap the element symmetry.

Java

public class Solution {
    public void rotate(int[][] matrix) {
    
        int row = matrix.length;
        int column = matrix[0].length;
        
        for(int i=0;i<row/2;i++){
            for(int j=0;j<column;j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[row-1-i][j];
                matrix[row-1-i][j] = temp;
            }
        }
        
        for(int i=0;i<row;i++){
            for(int j=i;j<column;j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容