LeetCode Brushing Notes _48. Rotating image

The topic is from LeetCode

48. Rotate image

Other solutions or source code can be accessed: tongji4m3

description

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 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

In the peripheral rotation, you only need to rotate [0,0], to [0,n-2] and the corresponding four corners in turn.
Because it is a square matrix, we define lo and hi to represent the upper layer of traversal and the lower layer of traversal. , And also useful for left and right

detail

Code

public void rotate(int[][] matrix)
{
    
    
    int lo = 0, hi = matrix.length - 1;
    while(lo<hi)
    {
    
    
        for (int i = 0; i < hi - lo; i++)
        {
    
    
            int temp=matrix[lo][lo+i];
            matrix[lo][lo + i] = matrix[hi - i][lo];
            matrix[hi - i][lo] = matrix[hi][hi - i];
            matrix[hi][hi - i] = matrix[lo + i][hi];
            matrix[lo + i][hi] = temp;
        }
        ++lo;
        --hi;
    }
}

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108192448