LeetCode-48~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?

算法分析

方法一
  • 將原始矩陣中的元素復制到新矩陣中
  • 矩陣中元素位置計算:橫縱坐標分別計算
    • 原始矩陣中橫坐標為新矩陣中縱坐標
    • 原始矩陣中縱坐標j為新矩陣中height-j-1坐標
Java代碼
public class Solution {
    public void rotate(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
        int height = matrix.length;
        int weight = matrix[0].length;
        
        if (height != weight) return;
        
        int[][] temp = new int[weight][height];
        for (int i = 0; i < height; i ++) {
            for (int j = 0; j < weight; j ++) {
                temp[i][j] = matrix[i][j];
            }
        }

        for (int i = 0; i < height; i ++) {
            for (int j = 0; j < weight; j ++) {
                matrix[i][j] = temp[height - j- 1][i];
            }
        }    
    }
}
方法二:

原地坐標轉換。如圖所示:


原地坐標轉換
Java代碼
public class Solution {
    public void rotate(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
        int height = matrix.length;
        int weight = matrix[0].length;
        
        if (height != weight) return;
        
        int temp = 0;
        
        //原地坐標轉換
        for (int i = 0; i < height / 2; i ++) {
            for (int j = i; j < height - 1 - i; j ++) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[height - j - 1][i];
                matrix[height - j - 1][i] = matrix[height - i - 1][height - j - 1];
                matrix[height - i - 1][height - j - 1] = matrix[j][height - i - 1];
                matrix[j][height - i - 1] = temp;
            }
        }
    }
}

參考

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容