题解 | #蛇形矩阵#
蛇形矩阵
http://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e
通过计算坐标,按题目的蛇形要求向二维数组中添加元素,最后输出二维数组。
n = int(input()) x, y = 0, 0 out = 0 result = [[0] * n for _ in range(n)] while True: out += 1 result[x][y] = out # 坐标向右上方移动 if x - 1 in range(0, n) and y + 1 in range(0, n): x -= 1 y += 1 else: x, y = y, x # 取对称位置 if x + 1 in range(0, n): x += 1 y = 0 else: break for i in range(n): for j in range(0, n - i): print(result[i][j], end=(' ')) print()