3 line Python in place solution


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

    This algorithm iterates the four equal size pieces of the matrix. If the side length n is even, just divide in halves. If it is odd, make the piece of size (n/2+n%2, n/2), as shown below. Then use the comma notation in python to swap them in place.

    0_1475445040419_upload-3b938ffb-7f0a-44c4-a24c-c1f9f1e7a3dd


Log in to reply
 

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