- Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathrotate_image.py
33 lines (26 loc) · 642 Bytes
/
rotate_image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""
You are given an n x n 2D mat representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
"""
# clockwise rotate
# first reverse up to down, then swap the symmetry
# 1 2 3 7 8 9 7 4 1
# 4 5 6 => 4 5 6 => 8 5 2
# 7 8 9 1 2 3 9 6 3
defrotate(mat):
ifnotmat:
returnmat
mat.reverse()
foriinrange(len(mat)):
forjinrange(i):
mat[i][j], mat[j][i] =mat[j][i], mat[i][j]
returnmat
if__name__=="__main__":
mat= [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(mat)
rotate(mat)
print(mat)