需要将方形矩阵顺时针旋转 90 度。适用于第一个循环,但在进入下一个周期的那一刻,索引超出了范围

need to rotate a square matrix by 90degree clockwise. works for 1st loop but gives index out of range the moment it enters next cycle

提问人:Sankalp Rawat 提问时间:10/9/2023 最后编辑:Sankalp Rawat 更新时间:10/9/2023 访问量:48

问:

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]] 

输出 - [[7,2,1],[4,5,6],[9,8,3]] (这个结果是如果我在第一个周期后停止 j 循环,如果我让它走得更远,它会产生索引错误)

Python 列表 矩阵 嵌套循环 嵌套列表

评论

0赞 nokla 10/9/2023
请设置问题的格式

答:

2赞 Andrej Kesely 10/9/2023 #1

我建议使用转置操作(例如)来简化代码: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]]
2赞 RomanPerekhrest 10/9/2023 #2

替代方案:np.rot90 用于灵活的 90 度旋转:numpy

import numpy as np

arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
out = np.rot90(arr, 1, axes=(1, 0))

array([[7, 4, 1],
       [8, 5, 2],
       [9, 6, 3]])