class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
for i in range(0, len(matrix)//2):
x = i
y = len(matrix)-i-1
for j in range(i,len(matrix)-i-1):
prev = matrix[i][j]
l = i
r = j
for k in range(1,5):
l = l + x
r = r + y
curr = matrix[l][r]
matrix[l][r] = prev
prev = curr
temp = x
x = y
y = temp*(-1)
x = x + 1
y = y - 1
input = [[1,2,3],[4,5,6],[7,8,9]]
expected = [[7,4,1],[8,5,2],[9,6,3]]
output = [[7,2,1],[4,5,6],[9,8,3]]
(这个结果是如果我在第一个循环后停止 j 循环。如果我让它进一步运行,则会给出索引错误)
我建议使用转置操作(例如
zip(*iter)
)来简化代码:
def rotate_clockwise_inplace(m):
m[:] = [list(reversed(t)) for t in zip(*m)]
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rotate_clockwise_inplace(m)
print(m)
打印:
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]