1151. L05-04输出蛇形矩阵

n = int(input()) a = [[0 for i in range(n)] for j in range(n)] def numk(n, k): return k if k <= n else 2 * n - k def loc(n, k, l): if k <= n: i, j = 0, n - k else: i, j = k - n, 0 return i + l - 1, j + l - 1 for k in range(1, 2 * n): if k % 2 == 0: for l in range(1, 1 + numk(n, k)): i, j = loc(n, k, l) if l == 1: i2, j2 = loc(n, k - 1, 1) else: i2, j2 = loc(n, k, l - 1) a[i][j] = a[i2][j2] + 1 else: for l in range(numk(n, k), 0, -1): i, j = loc(n, k, l) if k == 1: a[i][j] = 1 else: if l == numk(n, k): i2, j2 = loc(n, k - 1, numk(n, k - 1)) else: i2, j2 = loc(n, k, l + 1) a[i][j] = a[i2][j2] + 1 for i in range(n): for j in range(n): print(a[i][j], end=" ") print()