python - 在我的旋转矩阵代码中找不到错误
问题描述
我知道有一种简单的方法使用转置将方阵旋转 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]]
这个矩阵足够大,以至于手动遍历算法变得乏味,就像我为较小的输入案例调试所做的那样。我的实现中的错误在哪里?
解决方案
你offset
的关了,试试
for offset in range(0, end-start):
推荐阅读
- jquery - 数组的 HTML 元素的选择器
- c++ - Character::BeginPlay() 未被调用
- javascript - 如何检查 ReportControl 对象上是否存在 Reportid 或不使用 *ngif?
- python - 如何从 HTML 中获取带有特定文本的行
- android - Flutter Development (flutter-dev) › 需要紧急帮助....由于 gradle 问题,我无法在 android 设备中运行 Flutter 应用程序并且无法构建 apk
- python - 第一次尝试 python,错误(“IndexError: index 8 is out of bounds for axis 0 with size 8”)和效率问题
- java - JavaFX 异常:内部图形尚未初始化
- python - Python - 有没有办法提出同一系列问题并存储每组答案,直到用户完成?
- python - 使用 python 和 VS Code 在“键盘”上导入错误
- python - Python usig pygame中的错误(AttributeError:'builtin_function_or_method'对象没有属性'right')