用户:旋风2005查看:0 回复:0 评论:0 创建时间:2020-02-04T12:13:18
通天塔最近有一道python操作题是蛇形填数,相信难倒了许多朋友(特别是院士5的时间特别短),于是我专门翻阅了一下资料,选了一篇能容易看明白的,再稍加改动。
废话不多说,直接上码:
def matrix(n):
#生成 n*n 0矩阵
l = [[0 for i in range(n)] for j in range(n)]
#设置边界条件
right = False
left = False
down = True
up = False
#设置边界
boundRight = n
boundLeft = 0
boundBottom = n
boundTop = 0
num = 0
#记录每次循环的坐标
startofX = 0
startofY = n - 1
while num < n * n:
#从[0][3]开始向下走
if down:
for _ in range(startofX, boundBottom):
num += 1
l[_][startofY] = num
down = not down
left = not left
#走完一层将右边的边界减一
boundRight -= 1
#设置下一次循环的起点位置
startofX = _
startofY -= 1
#到达底边界时向左走
if left:
for _ in range(startofY, boundLeft-1, -1):
num += 1
l[startofX][_] = num
left = not left
up = not up
#同样走完一层后底边界减一
boundBottom -= 1
#设置下一次循环的起点位置
startofY = _
startofX -= 1
#到达边界后向上走
if up:
for _ in range(startofX, boundTop-1, -1):
num +=1
l[_][startofY] = num
right = not right
up = not up
#这里走完之后左边增加一层,所以左边界加一
boundLeft += 1
startofX = _
startofY += 1
#到达顶层向右走
if right:
for _ in range(startofY, boundRight):
num += 1
l[startofX][_] = num
down = not down
right = not right
#同样走完以后顶层增加一层,上边界加一
boundTop += 1
startofY = _
startofX += 1
#打印矩阵
for i in range(n):
for j in range(n):
print(l[i][j], end=" ")
print()
a=int(input())#输入/输出
matrix(a)
(原文链接:https://blog.csdn.net/nilihzoo1o/article/details/79917409)
效果:
2 4 1 3 2
3 7 8 1 6 9 2 5 4 3
4 10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4
5 13 14 15 16 1 12 23 24 17 2 11 22 25 18 3 10 21 20 19 4 9 8 7 6 5
………………