个性化阅读
专注于IT技术分析

如何在Python中以螺旋形式(蜗牛或顺时针螺旋排序)格式化给定的数组(矩阵)

尽管你绝对不会在自己的工作中绝对不要使用这样的东西, 因为, 这根本没有意义, 但是对于年轻程序员的家庭作业来说, 这种练习非常普遍。这个想法很简单, 但是实现的方法不那么多, 你将拥有一个数组, 其中的多个数组在字面上大致是正方形或矩形, 而任务是创建一个返回单个数组的函数。例如, 按照螺旋形式或众所周知的蜗牛顺序排列的项目将分析以下示例和预期结果:

# Example 1.
matrix = [
    [1, 2, 3], [4, 5, 6], [7, 8, 9]
]
# Expected = [1, 2, 3, 6, 9, 8, 7, 4, 5]
print some_function(matrix)

# Example 2.
matrix = [
    [1, 2 , 3, 4, 5 ], [6, 7 , 8 , 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]
]             
# Expected = [1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12]
print some_function(matrix)

如果仍然不明白, 请参阅本文图像中的图形说明, 在该图中你可以看到结构化数组后的箭头形状为蜗牛。

实现

给定的结构始终是一个内部包含多个数组的单个数组, 因此你可以将其作为二次对象使用, 遍历每一行并根据生成的数组的状态使用一些标志返回到每一行:

"""
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example, Given the following matrix:
[
 [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]
]


It should return [1, 2, 3, 6, 9, 8, 7, 4, 5].
"""
def spiral_traversal(matrix):
    res = []
    if len(matrix) == 0:
        return res
    row_begin = 0
    row_end = len(matrix) - 1
    col_begin = 0
    col_end = len(matrix[0]) - 1

    while row_begin <= row_end and col_begin <= col_end:
        for i in range(col_begin, col_end+1):
            res.append(matrix[row_begin][i])
        row_begin += 1

        for i in range(row_begin, row_end+1):
            res.append(matrix[i][col_end])
        col_end -= 1

        if row_begin <= row_end:
            for i in range(col_end, col_begin-1, -1):
                res.append(matrix[row_end][i])
        row_end -= 1

        if col_begin <= col_end:
            for i in range(row_end, row_begin-1, -1):
                res.append(matrix[i][col_begin])
        col_begin += 1

    return res

使用此功能, 你将能够以所需的形式构造原始数组:

mat = [
    [1, 2, 3], [4, 5, 6], [7, 8, 9]
]

# [1, 2, 3, 6, 9, 8, 7, 4, 5]
print(spiral_traversal(mat))

编码愉快!

赞(0)
未经允许不得转载:srcmini » 如何在Python中以螺旋形式(蜗牛或顺时针螺旋排序)格式化给定的数组(矩阵)

评论 抢沙发

评论前必须登录!