第一种办法:每次旋转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上就不行了,不知道为啥