Solution with 2 flips


  • 0
    B
    class Solution(object):
        def rotate(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            """
            
            '''
            Easiest way to do it is two flip
            1 2 3  filp by main diagno  1 4 7  horizontal flip   7 4 1
            4 5 6 ====================> 2 5 8 =================> 8 5 2
            7 8 9                       3 6 9                    9 6 3
            '''
            n = len(matrix)
            
            # Rotate by main diagno
            for i in range(n):
                for j in range(i+1, n):
                    matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
            
            # horizontal flip
            for i in range(n):
                for j in range(n/2):
                    matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j]
    
    

Log in to reply
 

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