Rotate the image by 90 degrees (clockwise).
Given input matrix =
[
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
], rotate the input matrix in-place such that it becomes:
[
[9,5,1],
[10,6,2],
[11,7,3]
[12,8,4]
]
[[1,2,3,4], [[9,10,11,12], [[9,5,1],
[5,6,7,8], ==> [5,6,7,8], ==> [10,6,2],
[9,10,11,12]] [1,2,3,4]] [11,7,3],
[12,8,4]]
map(list, zip(*(matrix[::-1])))
Rotate the image by 90 degrees (anti-clockwise).
Given input matrix =
[
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
], rotate the input matrix in-place such that it becomes:
[
[4,8,12],
[3,7,11],
[2,6,10]
[1,5,9]
]
[[1,2,3,4], [[1,5,9], [[4,8,12],
[5,6,7,8], ==> [2,6,10], ==> [3,7,11],
[9,10,11,12]] [3,7,11], [2,6,10],
[4,8,12]] [1,5,9]]
map(list, zip(*matrix))[::-1]
如果matrix是n*n的, 然后需要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
*/
matrix[:] = matrix[::-1] # 记住要用matrix[:], 不然更改的不对
#matrix = matrix[::-1]
for i in range(len(matrix)):
for j in range(i+1, len(matrix)):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
/*
* 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
*/
matrix[:] = [each[::-1] for each in matrix]
3 for i in range(len(matrix)):
4 for j in range(i+1, len(matrix)):
5 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]