'''
生成 n*n的二维数字列表
再生成下标,再将下标按照题目要求排列,下标的排序即是自然数 1 2 3 4 5。。。的顺序
最后遍历下标列表和数字列表,将对应位置的数字进行更改
'''
n = int(input())
def func(n):
'''
@param n: 输入的数字
@return: 下标列表
'''
lis_node = []
node = (0, 0)
next_node = (0, 1)
if n == 1:
lis_node.append(node)
return lis_node
lis_node.append(node)
lis_node.append(next_node)
while True:
while next_node[1] > 0:
next_node = (next_node[0] + 1, next_node[1] - 1)
lis_node.append(next_node)
if next_node[0] == n - 1:
while next_node[0] < n and next_node[1] < n:
next_node = (next_node[0], next_node[1] + 1)
lis_node.append(next_node)
if next_node == (n - 1, n - 1):
return lis_node
while next_node[1] < n - 1:
next_node = (next_node[0] - 1, next_node[1] + 1)
lis_node.append(next_node)
next_node = (next_node[0] + 1, next_node[1])
lis_node.append(next_node)
while next_node[0] < n - 1:
next_node = (next_node[0] + 1, next_node[1] - 1)
lis_node.append(next_node)
else:
next_node = (next_node[0] + 1, next_node[1])
lis_node.append(next_node)
while next_node[0] > 0:
next_node = (next_node[0] - 1, next_node[1] + 1)
lis_node.append(next_node)
if next_node[1] == n - 1:
while next_node[0] < n and next_node[1] < n:
next_node = (next_node[0] + 1, next_node[1])
lis_node.append(next_node)
while next_node[0] < n - 1:
next_node = (next_node[0] + 1, next_node[1] - 1)
lis_node.append(next_node)
next_node = (next_node[0], next_node[1] + 1)
lis_node.append(next_node)
if next_node == (n - 1, n - 1):
return lis_node
while next_node[1] < n - 1:
next_node = (next_node[0] - 1, next_node[1] + 1)
lis_node.append(next_node)
else:
next_node = (next_node[0], next_node[1] + 1)
lis_node.append(next_node)
lis_node = func(n)
lis = [[0 for _ in range(n)] for i in range(n)] # n*n的数字列表
val = 1 # 第一个填入的值,此后每遍历出一个下标,就将该值加一填入
for ind in lis_node:
lis[ind[0]][ind[1]] = val
val += 1
for i in range(n):
for k in range(n):
print(lis[i][k], end=' ')
print()
水平优先,写的可能有些复杂,感觉难得地方在边界判断上
全部评论
(0) 回帖