https://leetcode-cn.com/probl...python
由外到內依次移動,每次之移動一個元素,因此空間複雜度是 O(1) 。函數
移動順序是從左上角開始,每次開始移動一直要把對應的四個位置輪換一邊才結束,再執行第二個位置。code
求下一個位置的函數:leetcode
def next_xy(x, y, s): return y, s - 1 - x
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ def next_xy(x, y, s): return y, s - 1 - x n = len(matrix) i = 0 for i in range(n): l = n - i * 2 if l < 2: break for j in range(l-1): x, y = 0, j t = matrix[x+i][y+i] for k in range(4): nx, ny = next_xy(x, y, l) print(x, y, nx, ny) print(t, matrix[nx+i][ny+i]) tt = matrix[nx+i][ny+i] matrix[nx+i][ny+i] = t x, y, t = nx, ny, tt
歡迎來個人博客: https://codeplot.top/
個人博客刷題分類:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/get