Simple one-pass in-place Python solution

  • 0

    For a certain cell matrix[i][j], we compute the place of it if it rotates 90 degree, 180 degree, and 270 degree. And we simply reassign it one by one. This works fine if the length of matrix is even. If it is odd, we need to add either i or j by 1 in order to rotate the number in the middle as well. So we just change the ending condition to be n/2+n%2.

    class Solution(object):
        def rotate(self, matrix):
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            n = len(matrix)
            for i in xrange(n/2):
                for j in xrange(n/2+n%2):
                    matrix[i][j], matrix[j][n-i-1], matrix[n-i-1][n-j-1], matrix[n-j-1][i] = matrix[n-j-1][i], matrix[i][j], matrix[j][n-i-1], matrix[n-i-1][n-j-1]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.