LeetCode-48. Rotate Image-Array

48. Rotate image

Title description

Given an n × n two-dimensional matrix matrix represents an image. Please rotate the image 90 degrees clockwise.

You have to rotate the image in place, which means you need to directly modify the input two-dimensional matrix. Please do not use another matrix to rotate the image.

Example 1:

Insert picture description here

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9 ,6,3]]
Example 2:
Insert picture description here

Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15 ,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Example 3:

Input: matrix = [[1]]
Output: [[1]]
Example 4:

Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]

Problem-solving ideas

Use auxiliary array

    /**
     * 使用辅助数组
     * @param matrix
     */
    public void rotate_1(int[][] matrix) {
    
    
        int n = matrix.length;
        int[][] matrix_new = new int[n][n];
        for (int i = 0; i < n; i++) {
    
    
            for (int j = 0; j < n; j++) {
    
    
                matrix_new[j][n - i - 1] = matrix[i][j];
            }
        }
        for (int i = 0; i < n; i++) {
    
    
            for (int j = 0; j < n; j++) {
    
    
                matrix[i][j] = matrix_new[i][j];
            }
        }
    }

Rotate in place

    /**
     * 原地旋转
     */

    public void rotate_2(int[][] matrix) {
    
    
        int n = matrix.length;
        for (int i = 0; i < n / 2; i++) {
    
    
            for (int j = 0; j < (n + 1) / 2; j++) {
    
    
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n - j - 1][i];
                matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
                matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
                matrix[j][n - i - 1] = temp;
            }
        }
    }

Use flip instead of rotate

  /**
     * 用翻转代替旋转
     */
    public void rotate(int[][] matrix) {
    
    
        int n = matrix.length;
        // 水平翻转
        for (int i = 0; i < n / 2; ++i) {
    
    
            for (int j = 0; j < n; ++j) {
    
    
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n - i - 1][j];
                matrix[n - i - 1][j] = temp;
            }
        }
        // 主对角线翻转
        for (int i = 0; i < n; ++i) {
    
    
            for (int j = 0; j < i; ++j) {
    
    
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }

Guess you like

Origin blog.csdn.net/qq_35655602/article/details/115147256