问题描述
小C发现了一种奇特的图案,叫做螺旋阵列。它由一串0和1组成,看起来像一个由外向内旋转的图形。小C想知道,能否根据给定的宽度来生成这样一个螺旋图案。
例如,宽度为5时的螺旋阵列如下:
11111
00001
11101
10001
11111
宽度为10时的螺旋阵列如下:
1111111111
0000000001
1111111101
1000000101
1011110101
1010010101
1010000101
1011111101
1000000001
1111111111
小C想知道,对于任意给定的宽度 n
,是否能生成对应的螺旋图案,并且以一个二维数组的形式输出。
代码
def solution(width):
# Please write your code here
assert width > 1
if width == 2:
return [[1, 1], [0, 1]]
if width == 3:
return [[1, 1, 1], [0, 0, 1], [1, 1, 1]]
base = solution(width - 2)
res = [[1] * width, [0] * width]
res[1][-1] = 1
for i in range(width - 3, -1, -1):
res.append(base[i][::-1] + [0, 1])
res[-1][-2] = 1
return res
if __name__ == "__main__":
# You can add more test cases here
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]])