48. Rotate Image

weixin_33785972發表於2018-04-28

第一種辦法:每次旋轉4個值

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[0])
        i = 0
        j = 0
        while i < n / 2:
            j = i
            while j < n - 1 - i:
                temp = matrix[i][j]
                matrix[i][j] = matrix[n-1-j][i]
                matrix[n-1-j][i] = matrix[n-1-i][n-1-j]
                matrix[n-1-i][n-1-j] = matrix[j][n-1-i]
                matrix[j][n-1-i]= temp
                j += 1
            i += 1

第二種做法:
先沿著n-1對稱軸進行對稱變換,然後上下兩半進行對稱反轉

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 range(n-1):
            for j in range(n-1-i):
                matrix[i][j],matrix[n-1-j][n-1-i] = matrix[n-1-j][n-1-i],matrix[i][j]
        for i in range(n/2):
            for j in range(n):
                matrix[i][j], matrix[n-1-i][j] = matrix[n-1-i][j],matrix[i][j]

第三種做法
先轉置矩陣,然後左右對稱一下

class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        print matrix
        n = len(matrix[0])
        matrix = map(list, zip(*matrix))
        print matrix
        for j in range(n/2):
            for i in range(n):
                matrix[i][j],matrix[i][n-1-j] = matrix[i][n-1-j],matrix[i][j]
        print matrix
s = Solution()
s.rotate([[1,2,3],[4,5,6],[7,8,9]])

這種辦法我在本地上可以做,但是在leetcode上就不行了,不知道為啥

相關文章