螺旋阵列的神秘艺术

170 阅读3分钟

螺旋阵列生成题解

题目描述

小C发现了一种奇特的图案,叫做螺旋阵列。它由一串0和1组成,看起来像一个由外向内旋转的图形。小C想知道,能否根据给定的宽度来生成这样一个螺旋图案。

例如:

  • 宽度为5时的螺旋阵列如下:
    11111
    00001
    11101
    10001
    11111
    
  • 宽度为8时的螺旋阵列如下:
    11111111
    00000001
    11111101
    10000101
    10101101
    10111101
    10000001
    11111111
    

小C想知道,对于任意给定的宽度 n,是否能生成对应的螺旋图案,并且以一个二维数组的形式输出。

测试样例

样例1: 输入:width = 5 输出:

[[1, 1, 1, 1, 1], 
 [0, 0, 0, 0, 1], 
 [1, 1, 1, 0, 1], 
 [1, 0, 0, 0, 1], 
 [1, 1, 1, 1, 1]]

样例2: 输入:width = 8 输出:

[[1, 1, 1, 1, 1, 1, 1, 1], 
 [0, 0, 0, 0, 0, 0, 0, 1], 
 [1, 1, 1, 1, 1, 1, 0, 1], 
 [1, 0, 0, 0, 0, 1, 0, 1], 
 [1, 0, 1, 0, 0, 1, 0, 1], 
 [1, 0, 1, 1, 1, 1, 0, 1], 
 [1, 0, 0, 0, 0, 0, 0, 1], 
 [1, 1, 1, 1, 1, 1, 1, 1]]

样例3: 输入:width = 2 输出:

[[1, 1], 
 [0, 1]]

题解

为了生成螺旋阵列,我们需要从外向内一层一层地绘制1和0。以下是详细步骤:

  1. 初始化一个宽度为 width 的二维数组 matrix,所有元素初始为0。
  2. 定义边界 top, bottom, left, right,初始值分别为0, width-1, 0, width-1
  3. 使用一个循环来填充矩阵,循环条件是 top <= bottomleft <= right
  4. 按照顺时针方向依次填充上边界、右边界、下边界和左边界,填充完一层后,调整边界值以缩小填充范围,继续下一层的填充。
  5. 返回最终生成的 matrix

以下是完整的代码实现:

def solution(width):
    matrix = [[0] * width for _ in range(width)]
    top, bottom = 0, width - 1
    left, right = 0, width - 1
    while top <= bottom and left <= right:
        for i in range(left, right + 1):
            matrix[top][i] = 1
        top += 1
        
        for i in range(top, bottom + 1):
            matrix[i][right] = 1
        right -= 1
        
        if top <= bottom:
            for i in range(right, left - 1, -1):
                matrix[bottom][i] = 1
            bottom -= 1
        
        if left <= right:
            for i in range(bottom, top - 1, -1):
                matrix[i][left] = 1
            left += 1
    return matrix

if __name__ == "__main__":
    # 测试用例
    print(solution(5) == [[1, 1, 1, 1, 1], [0, 0, 0, 0, 1], [1, 1, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]])
    print(solution(8) == [[1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 0, 0, 1, 0, 1], [1, 0, 1, 0, 0, 1, 0, 1], [1, 0, 1, 1, 1, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1]])
    print(solution(2) == [[1, 1], [0, 1]])

总结

这道题主要考察了二维数组的操作以及如何按顺时针方向填充数组。通过定义边界并逐层缩小填充范围,我们可以很方便地生成螺旋阵列。希望这个题解对你有所帮助!