Problem Definition:
You are given a n x n 2D matrix representing an image.
Rotate the image by degrees (clockwise).
Follow up:
Could do this in-place?
Solution:
Rotate 90 degrees clockwise, which is the axis of the center of the table (picture), and all coordinates are rotated. coordinate mapping in rotation, try it with a small example:
For a 3x3 table, the cell mapping is this:
00-->02-->22-->20-->00
01-->12-->21-->10-->01
02-->22-->20-->00-->02
(The last line of this transformation is the same set of elements as the first line, not really, just to show the relationship of cell coordinates.) )
In the 12th column, the adjacent sub-columns are the same, away from the child columns, and the n-1 are added together.
Let's look at a larger example:
00 will run to the 03 position, 03 will run to 33 position .... A set of cells (a blue fill) is marked:
01 will run to the 13 position, 13 will run to 32 position ... This group is indicated in red:
02 What's the same, Green says:
In such a lap, the outer cells are all gone, leaving a 2 x 2 table inside. Go on ....
Cyclic assignment, Space complexity O (1)
1 #@param {integer[][]} matrix2 #@return {void} does not return anything, modify matrix In-place instead.3 defRotate (matrix):4m=len (Matrix)5 ifM<=1:6 return7 forIinchRange (m-1):8 forJinchRange (i,m-1-i):9z=Matrix[i][j]TenMatrix[i][j]=matrix[m-1-J] [I] OneMatrix[m-1-j][i]=matrix[m-1-i][m-1-J] AMatrix[m-1-i][m-1-j]=matrix[j][m-1-i] -Matrix[j][m-1-i]=z
leetcode#48 Rotate Image