Python螺旋矩阵遍历

在 Python 中以螺旋顺序遍历并列出二维矩阵的元素。

在编辑器中尝试

概述

螺旋矩阵遍历是一个经典的多维数组问题。它需要顺时针遍历外部边界并逐渐缩小边界。

我们维护四个指针:“top”、“bottom”、“left”和“right”来跟踪未访问的矩阵部分的边界。

通过从左到右、从上到下、从右到左、从下到上的顺序遍历,我们系统地覆盖了所有单元格。

代码和执行输出

顺时针螺旋遍历显示索引操纵。

def spiral_order(matrix):
    if not matrix:
        return []
        
    result = []
    top, bottom = 0, len(matrix) - 1
    left, right = 0, len(matrix[0]) - 1
    
    while top <= bottom and left <= right:
        # Traverse Right
        for col in range(left, right + 1):
            result.append(matrix[top][col])
        top += 1
        
        # Traverse Down
        for row in range(top, bottom + 1):
            result.append(matrix[row][right])
        right -= 1
        
        if top <= bottom:
            # Traverse Left
            for col in range(right, left - 1, -1):
                result.append(matrix[bottom][col])
            bottom -= 1
            
        if left <= right:
            # Traverse Up
            for row in range(bottom, top - 1, -1):
                result.append(matrix[row][left])
            left += 1
            
    return result

grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print("Matrix Spiral Order:")
print(spiral_order(grid))
端子输出
Matrix Spiral Order:
[1, 2, 3, 6, 9, 8, 7, 4, 5]

逐步实施

  • 2D图形渲染和螺旋路径跟踪
  • 数据引擎中的网格布局导航模式
  • 高级算法评估测试

常见问题解答

螺旋遍历的时间复杂度是多少?

时间复杂度为 O(m * n),其中 m 是行,n 是列,因为我们只访问网格中的每个单元一次。

相关主题