AcWing 756. 蛇形矩阵 - Python3
原题链接
简单
def main():
n, m = map(int, input().split())
matrix = [[-1] * m for _ in range(n)]
nums = [i for i in range(1, n * m + 1)]
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
x = y = di = 0
for i in range(n * m):
matrix[x][y] = nums[i]
x_next, y_next = x + dx[di], y + dy[di]
if 0 <= x_next < n and 0 <= y_next < m and matrix[x_next][y_next] == -1:
x, y = x_next, y_next
else:
di = (di + 1) % 4
x, y = x + dx[di], y + dy[di]
for row in matrix:
for i in row:
print(i, end = ' ')
print()
main()