leetcode之圖像旋轉(Rotate Image)

1.新建一個數組,將原數組的數據按規律複製到新數組,這種方法做不到in-place,佔用了額外一個數組的空間

newx = y;
newy = n-1-x;

2.我們可以按ring by ring的順序進行操作
交換在每個ring上的4個點之間進行

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for(int x = 0; x <= (n - 1) >> 1; x++) {
            for(int y = x; y <= n - 2 - x; y++) {
                int newx1 = y;
                int newy1 = n - 1 - x;
                int newx2 = newy1;
                int newy2 = n - 1 - newx1;
                int newx3 = newy2;
                int newy3 = n - 1 - newx2;
                int temp = matrix[newx1][newy1];

                matrix[newx1][newy1] = matrix[x][y];
                matrix[x][y] = matrix[newx3][newy3];
                matrix[newx3][newy3] = matrix[newx2][newy2];
                matrix[newx2][newy2] = temp;

            }
        }
    }
}

這裏寫圖片描述
3.將上下的行進行反轉,然後按主對角線進行對稱交換;這這種方法也很容易做到逆時針旋轉。

/*
 * clockwise rotate
 * first reverse up to down, then swap the symmetry 
 * 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
*/

/*
 * anticlockwise rotate
 * first reverse left to right, then swap the symmetry
 * 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
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章