48. Rotate Image
- Total Accepted: 84852
- Total Submissions: 232792
- Difficulty: Medium
- Contributors: Admin
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
General Idea:
You need to first flip matrix upside down. Then swap elements mirror to the diagonal.
<span class="hljs-comment"> # 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</span>
Code
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ matrix[:] = zip(*matrix[::-1])
Idea
Pythonic way.
Code
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ self.upside_down(matrix) self.mirror_diag(matrix) def upside_down(self, matrix): n = len(matrix) for i in xrange(n/2): for j in xrange(n): matrix[i][j], matrix[n-i-1][j] = matrix[n-i-1][j], matrix[i][j] def mirror_diag(self, matrix): n = len(matrix) for i in xrange(n): for j in xrange(i+1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
Idea
Self implement upside down and mirror.
Reference:
https://discuss.leetcode.com/topic/15295/seven-short-solutions-1-to-7-lines
https://discuss.leetcode.com/topic/6796/a-common-method-to-rotate-the-image/2