[One Question of the Day] Likou 48. Rotate the image

Title description ( portal )

Given an n × n two-dimensional matrix represents an image.

Rotate the image 90 degrees clockwise.

Description:

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

Example 1:

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]


Example 2:

给定 matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

原地旋转输入矩阵,使其变为:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

Ideas

By observing the array, we can rotate the array by 90 degrees, which is equivalent to flipping the array to the left and right according to the middle column, and then flipping the inverted array according to the subdiagonal line.

Code

class Solution {
    
    
    public void rotate(int[][] matrix) {
    
    
        int ROW = matrix.length;
        int COL = matrix[0].length;
        // 首先将数组元素对半交换
        for (int i = 0; i < COL; i++) {
    
    //
            for (int j = 0; j < ROW/2; j++) {
    
    
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][ROW-j-1];
                matrix[i][ROW-j-1] = temp;
            }
        }
        // 主对角线交换
        for (int i = 0; i < COL; i++) {
    
    
            for (int j = 0; j < ROW-i; j++) {
    
    
                int temp = matrix[i][j];
                matrix[i][j] = matrix[COL-1-j][ROW-1-i];
                matrix[COL-1-j][ROW-1-i] = temp;
            }
        }

    }
}

Guess you like

Origin blog.csdn.net/weixin_45532227/article/details/111401051