You are given an_n_x_n_2D matrix representing an image.
Rotate the image by90
degrees (clockwise).
Have you met this question in a real interview?
Yes
Example
Given a matrix
[
[1,2],
[3,4]
]
rotate it by 90 degrees (clockwise), return
[
[3,1],
[4,2]
]
method 1
using the coordinates induct for the next position
- have to come up with the originate point 0 <= r < (n + 1) / 2 and 0 <= c < n / 2
- using the first induct for the next four points r, c => c, n - 1 - r => n - 1 - c, n - 1 - r => n - 1 - c, r
def rotate(self, matrix):
# write your code here
if not matrix or not matrix[0]:
return
n = len(matrix)
for r in range((n + 1) / 2):
for c in range(n / 2):
tmp = matrix[r][c]
matrix[r][c] = matrix[n - 1 - c][r]
matrix[n - 1 - c][r] = matrix[n - 1 - r][n - 1 - c]
matrix[n - 1 - r][n - 1 - c] = matrix[c][n - 1 - r]
matrix[c][n - 1 - r] = tmp