1 """
2 You are given an n x n 2D matrix representing an image.
3 Rotate the image by 90 degrees (clockwise).
4 Note:
5 You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
6 Example 1:
7 Given input matrix =
8 [
9 [1,2,3],
10 [4,5,6],
11 [7,8,9]
12 ],
13 rotate the input matrix in-place such that it becomes:
14 [
15 [7,4,1],
16 [8,5,2],
17 [9,6,3]
18 ]
19 Example 2:
20 Given input matrix =
21 [
22 [ 5, 1, 9,11],
23 [ 2, 4, 8,10],
24 [13, 3, 6, 7],
25 [15,14,12,16]
26 ],
27 rotate the input matrix in-place such that it becomes:
28 [
29 [15,13, 2, 5],
30 [14, 3, 4, 1],
31 [12, 6, 8, 9],
32 [16, 7,10,11]
33 ]
34 """
35 class Solution:
36 def rotate(self, matrix):
37 """
38 Do not return anything, modify matrix in-place instead.
39 """
40 matrix.reverse() #[::-1]
41 for i in range(len(matrix)):
42 for j in range(i): #注意这里是range(i),交换一遍就行
43 matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]