如何使用循环将矩阵中的顺时针螺旋输出作为独立输出?

How can I use a loop to get clockwise spiral output in matrix as an independent output?

This image 解释了我要解决的问题。

这是我尝试的解决方案:

matrix = [[1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15],
      [16, 17, 18, 19, 20]]
i = 0
y = (len(matrix)-1)
while i < len(matrix):
    if i == 0:
        # print 1st row.
        for rows in matrix[i]:
            print(rows)

    # print all the last element of every rows, except 1st and last row.
    elif i != 0 and i != y:
        print(matrix[i][-1])

    # print the last row in reverse.
    elif i == y and i != 0:
        matrix[i].sort(reverse=True)
        for row in matrix[i]:
            print(row)

        print(matrix[i-1][0])       # print the 1st element of 3rd row.

        # print the 1st four elements of 2nd row.
        for r in matrix[1][0:4]:
            print(r)

        # finally print the rest of the elements in reverse.
        matrix[2].sort(reverse=True)
        for r_remain in matrix[2][1:4]:
            print(r_remain)

    i += 1

我的问题是,这个算法是对还是错?

其次,我的算法取决于输入矩阵的大小和内容。我怎样才能让它适用于任何输入?

可以使用 numpy 获得一个非常简短的解决方案,尽管这可能不符合作业的精神(库完成大部分工作):

import numpy

matrix = [[ 1,  2,  3,  4,  5],
          [14, 15, 16, 17,  6],
          [13, 20, 19, 18,  7],
          [12, 11, 10,  9,  8]]

def recurse(matrix):
    if not len(matrix): return
    for el in matrix[0]: print(el)
    recurse(numpy.rot90(matrix[1:]))

recurse(numpy.array(matrix))

这是一个适用于任意行数的完全通用的解决方案:

matrix = [[ 1,  2,  3,  4,  5],
          [12, 13, 14, 15,  6],
          [11, 10,  9,  8,  7]]

# print rows between lo_x..hi_x and columns between lo_y..hi_y (inclusive)
lo_x = lo_y = 0
hi_x = len(matrix[0]) - 1
hi_y = len(matrix) - 1

while lo_x <= hi_x and lo_y <= hi_y:
    for x in range(lo_x, hi_x+1): print(matrix[lo_y][x])
    lo_y += 1
    for y in range(lo_y, hi_y+1): print(matrix[y][hi_x])
    hi_x -= 1
    if not (lo_x <= hi_x and lo_y <= hi_y): break
    for x in reversed(range(lo_x, hi_x+1)): print(matrix[hi_y][x])
    hi_y -= 1
    for y in reversed(range(lo_y, hi_y+1)): print(matrix[y][lo_x])
    lo_x += 1

在每次迭代中,我们做一个螺旋(右、下、左、上)。中间的 break 是必需的,因为即使我们的 y 范围用完了,我们可能仍然有一个 x 范围。我添加了矩阵作为为什么需要 break 的示例(如果删除 break,它将产生错误输出)。