首页 > 解决方案 > 在我的旋转矩阵代码中找不到错误

问题描述

我知道有一种简单的方法使用转置将方阵旋转 90 度,但我正在编写一个解决方案,就好像我不知道那样(换句话说,我想做交换)。下面的一般想法是逐层交换。offset代表正在交换的层(从外到内)。

这是算法(注意它被包裹在 a 中,class因为那是Leetcode的东西):

class Solution:
    def rotate(self, matrix):
        for start in range(len(matrix)//2):
            end = len(matrix) - start - 1

            # swap all 4 coordinates:
            for offset in range(start, end): 
                # swap top_left over top_right
                temp, matrix[start+offset][end] = matrix[start+offset][end], matrix[start][start+offset]

                # swap top_right -> bottom_right 
                temp, matrix[end][end-offset] = matrix[end][end-offset], temp

                # swap bottom_right -> bottom_left
                temp, matrix[end-offset][start] = matrix[end-offset][start], temp

                # swap bottom_left -> top_left 
                matrix[start][start+offset] = temp

这适用于一些小矩阵的手动测试,以及 Leetcode 提交中较小的输入测试用例。但是,它在以下输入时失败:

[[ 2,  29,  20,  26,  16,  28],
 [12,  27,   9,  25,  13,  21],
 [32,  33,  32,   2,  28,  14],
 [13,  14,  32,  27,  22,  26],
 [33,   1,  20,   7,  21,   7],
 [ 4,  24,   1,   6,  32,  34]]

预期输出:

[[ 4,  33,  13,  32,  12,   2],
 [24,   1,  14,  33,  27,  29],
 [ 1,  20,  32,  32,   9,  20],
 [ 6,   7,  27,   2,  25,  26],
 [32,  21,  22,  28,  13,  16],
 [34,   7,  26,  14,  21,  28]]

我的输出:

[[ 4,  33,  13,  32,  12,   2],
 [24,   1,   7,  33,  27,  29],
 [ 1,  20,  32,   2,  14,  20],
 [ 6,  28,  32,  27,  25,  26],
 [32,  21,  22,   9,  13,  16],
 [34,   7,  26,  14,  21,  28]]

这个矩阵足够大,以至于手动遍历算法变得乏味,就像我为较小的输入案例调试所做的那样。我的实现中的错误在哪里?

标签: pythonalgorithmmatrix

解决方案


offset关了,试试

for offset in range(0, end-start):

推荐阅读