LeetCode48, how to rotate the matrix 90 degrees in place

This article originated from a personal public account : TechFlow , original is not easy, seek attention


Today is the 29th of LeetCode. Let ’s look at a simple matrix rotation problem.

Title

The requirement of the problem is very simple. Given a two-dimensional square matrix, it is required to return the result after the matrix is ​​rotated by 90 degrees .

Below we look at two examples:

answer

This animation is clear at a glance, which means that we need to rotate a two-dimensional matrix 90 degrees clockwise. We all understand this question very well, but there is a limitation in the question: we can't apply for other arrays to assist , which is to limit our space utilization.

If there is no such restriction, it is actually very easy, we only need to calculate the position after each coordinate rotation, we re-create an array and fill it in order.

We ignore the specific data in the matrix, and take a look at the coordinate changes before and after the matrix rotation. This is the coordinates before the matrix rotation:

After rotation, the coordinates become:

Looking at the two pictures above, we can see that for the coordinate (i, j), the result obtained after rotating it by 90 degrees should be (j, n-1-i). Here n is the number of rows.

After we have this formula, we can continue to promote it. We found that the point at (i, j) position reached (j, n-1-i) after rotation. And the point at (j, n-1-i) position is rotated to (n-1-i, n-1-j), and in the same way (n-1-i, n-1-j) is rotated to (n -1-j, i), and finally we found that (n-1-j, i) returned to (i, j) after rotation.

That is for one rotation, (i, j), ( j, n-1-i), (n-1-i, n-1-j), (n-1-j, i) four The elements in this position swapped positions with each other and did not affect other positions. In fact, this is also very easy to understand, because the problem is given by a square matrix.

We understand by looking at the following picture:

In other words, we only need to traverse a quarter of the matrix , and then get the 4 positions that are interchanged through the coordinates, and then exchange their elements.

Code

The code is really simple, only a few lines:

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """

        n = len(matrix)
        
        # 注意一下范围和下标即可
        for i in range(n//2):
            for j in range(i, n-1-i):
                matrix[i][j], matrix[j][n-1-i], matrix[n-1-i][n-1-j], matrix[n-1-j][i] = \
                matrix[n-1-j][i], matrix[i][j], matrix[j][n-1-i], matrix[n-1-i][n-1-j]

Today's article is just that. If you feel something rewarded, please follow or repost it. Your effort is very important to me.

Published 117 original articles · Like 61 · Visits 10,000+

Guess you like

Origin blog.csdn.net/TechFlow/article/details/105475070