当前位置: 代码迷 >> 综合 >> Leetcode 48. Rotate Image (python)
  详细解决方案

Leetcode 48. Rotate Image (python)

热度:25   发布时间:2024-02-24 21:02:42.0

Leetcode 48. Rotate Image

  • 题目
  • 解法:
  • follow up1: 逆时针旋转90度
  • follow up 2:旋转180度

题目

在这里插入图片描述

解法:

先transpose,然后把每行reverse

class Solution:def rotate(self, matrix: List[List[int]]) -> None:"""Do not return anything, modify matrix in-place instead."""n = len(matrix)# transposefor i in range(n):for j in range(i,n):matrix[i][j],matrix[j][i] = matrix[j][i],matrix[i][j]# reverse by rowfor i in range(n):matrix[i] = matrix[i][::-1]

follow up1: 逆时针旋转90度

先reverse行,再transpose

class Solution:def rotate(self, matrix: List[List[int]]) -> None:"""Do not return anything, modify matrix in-place instead."""n = len(matrix)# reverse by rowfor i in range(n):matrix[i] = matrix[i][::-1]# transposefor i in range(n):for j in range(i,n):matrix[i][j],matrix[j][i] = matrix[j][i],matrix[i][j]

follow up 2:旋转180度

先reverse行,然后reverse列

class Solution:def rotate(self, matrix: List[List[int]]) -> None:"""Do not return anything, modify matrix in-place instead."""n = len(matrix)# reverse rowfor i in range(n):matrix[i] = matrix[i][::-1]# reverse columnfor j in range(n):up = 0down = n-1while up<down:matrix[up][j],matrix[down][j] = matrix[down][j],matrix[up][j]up+=1down-=1
  相关解决方案