leetcode48

48. Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:

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.

Example 1:

Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

Idea

tranpose firtly and mirror translate second.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
"""
@param matrix: a lists of integers
@return: nothing
"""
def rotate(self, matrix):
# write your code here
if matrix == None or len(matrix) == 0:
return None
matrix = self.transpose(matrix)
matrix = self.mirror(matrix)
return matrix

def mirror(self, matrix):
for i in range(len(matrix)):
matrix[i].reverse()
return matrix

def transpose(self, matrix):
n = len(matrix)
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
return matrix

Python

1
2
3
4
# list reverse
matrix[i].reverse()
# exchange
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]