将数组旋转90度(旋转图像)

2023-04-25 11:30:13 浏览数 (2)

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?

思路 : 1、将旋转拆列解为对矩阵一圈一圈的做旋转,如下图中的①②。 2、若圈为NxN, 则需要对n-1个数进行旋转

3、旋转对应规则 假设对应矩阵左上角坐标为(LR,LC),右下角坐标为(RR,RC)。则 需要旋转的个数times = RC -LC; 左上角元素开始,从左到右进行旋转。 每次旋转一个数,会影响四个数的位置,其中对应关系为: m[LR][LC i] = m[RR - i][LC] m[RR - i][LC] = m[RR][RC - i] m[RR][RC - i] = m[LR i][RC] m[LR i][RC] = m[LR][LC i] (i表示每一圈的第i次,从 0 开始) 如下图中相同颜色,则是相关的四个数,这四个数按照上述的关系进行交换。

代码如下:

代码语言:javascript复制
public class RotateMatrix{
    public static void rotate(int[][] matrix) {
        int LR = 0;
        int LC = 0;
        int RR = matrix.length - 1;
        int RC = matrix[0].length - 1;
        while(LR < RR){ //只要还保持对应的左右对角关系就继续
            rotateEdge(matrix, LR  , LC  , RR--, RC--);
        }
    }

    public static void rotateEdge(int[][] m, int LR, int LC, int RR, int RC){
        int times = RC - LC; //旋转的数字个数
        int tmp = 0;
        for (int i = 0; i != times; i  ) { 
            tmp = m[LR][LC   i];
            m[LR][LC   i] = m[RR - i][LC];
            m[RR - i][LC] = m[RR][RC - i];
            m[RR][RC - i] = m[LR   i][RC];
            m[LR   i][RC] = tmp;
        }
    }

    public static void printMatrix(int[][] matrix) {
        for (int i = 0; i != matrix.length; i  ) {
            for (int j = 0; j != matrix[0].length; j  ) {
                System.out.print(matrix[i][j]   " ");
            }
            System.out.println();
        }
    }


    public static void main(String[] args) {
        int [][] matrix = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} };
        printMatrix(matrix);
        rotate(matrix);
        System.out.println("==================");
        printMatrix(matrix);
    }
}

0 人点赞