Leetcode -- 48. 旋转图像

Problem: 48. 旋转图像

思路

模拟旋转过程

解题方法

模拟旋转过程,将整个矩阵分解为多个只有四边的正方形,然后根据旋转过程中每个坐标的变化规律依次旋转;每次只转四个边上的一个值,循环一条边,最终即可将该四边的正方形旋转到正确位置;然后再旋转另外一个正方形,当所有的正方形旋转到对应位置之后,即整个矩阵完成玲旋转过程。

image.png

复杂度

时间复杂度:

添加时间复杂度, 示例: $O(n)$

空间复杂度:

添加空间复杂度, 示例: $O(n)$

Code

class Solution {
    public void rotate(int[][] matrix) {
        int len = matrix.length;

        int tagLen = len;
        int coordinateX = 0;
        int coordinateY = 0;
        while (tagLen > 1) {

            int temp;
            for (int j = 0; j < len - coordinateY-coordinateX - 1; j++) {
                temp = matrix[coordinateX][coordinateY + j];
                matrix[coordinateX][coordinateY + j] = matrix[len-coordinateX-j-1][coordinateY];
                matrix[len-coordinateX-j-1][coordinateY] = matrix[len-1-coordinateX][len-j-coordinateY-1];
                matrix[len-1-coordinateX][len-j-coordinateY-1] = matrix[coordinateX + j][len-1-coordinateY];
                matrix[coordinateX + j][len-1-coordinateY] = temp;

                // for (int row = 0; row < len; row++) {
                //     for (int col = 0; col < len; col++) {
                //         System.out.print(matrix[row][col] + " ");
                //     }
                //     System.out.println("\n");
                // }
            }

            tagLen -= 2;
            coordinateX ++;
            coordinateY ++;
        }
    }
}
posted @ 2023-12-14 22:55  扫地の小沙弥  阅读(23)  评论(0)    收藏  举报