标签:pre 元素 src image code 矩阵 sel ever lis
转置加翻转
思路:
先把矩阵转置,然后把每一行元素翻转。即遍历元素,交换matrix[i][j]和matrix[j][i],然后翻转每一个子数组。
代码:
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) for i in range(n): for j in range(i,n): matrix[j][i],matrix[i][j] = matrix[i][j],matrix[j][i] for i in range(n): matrix[i].reverse()
遍历旋转
思路:
遍历交换4条边上的元素。
代码:
class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ n = len(matrix[0]) for i in range(n // 2 + n % 2): for j in range(n // 2): tmp = matrix[n - 1 - j][i] matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1] matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 -i] matrix[j][n - 1 - i] = matrix[i][j] matrix[i][j] = tmp
标签:pre 元素 src image code 矩阵 sel ever lis
原文地址:https://www.cnblogs.com/nilhxzcode/p/12991714.html