[leetcode] matrix

48. Rotate Image

Matrix Rotation Problems
Solution Template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
* 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
*/

/*
* anticlockwise rotate
* first reverse left to right, then swap the symmetry
* 1 2 3 3 2 1 3 6 9
* 4 5 6 => 6 5 4 => 2 5 8
* 7 8 9 9 8 7 1 4 7
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
def (self, matrix: 'List[List[int]]') -> 'None':
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return
matrix.reverse()
n = len(matrix)
cnt = 0
for i in range(len(matrix)):
j = i
while j < len(matrix):
temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
j += 1