简洁版:
# 由内到外输出数字矩阵
def SpinMatrix(size, a = 0, b = 0):
if size % 2 == 0:
size += 1
spinMatrix = [([0] * size) for x in range(size)]
x, y, param, side = int(size/2), int(size/2), int(size/2), size-1
for i in range(1, size**2 + 1):
spinMatrix[y][x] = i
if x>=y and y<=-x+side:
x+=1
elif x>y and y>-x+side:
y+=1
elif x<=y and y>-x+side:
x-=1
elif x<y and y<=-x+side:
y-=1
for mt in spinMatrix:
print("t".join(map(lambda x:str(x), mt)))
SpinMatrix(5)
代码:
#内螺旋矩阵
def interSpiralMatrix(size, a=0, b=0):
#size必须是奇数
if (size % 2 != 1):
size += 1
#初始化矩阵
spiralMatrix = [([0] * size) for i in range(size)]
# print(spiralMatrix)
x, y, side = int(size / 2), int(size / 2), size - 1
param = int(size / 2)
for i in range(1, size ** 2 + 1):
spiralMatrix[y][x] = i
# 输出数字坐标
# if i == size:
# print(x-param,y-param)
# break
# 输出坐标上的数字
# if x-param == a and y-param == b:
# print(i)
# break
#通过直线划分为4个区域,y=x和y=-x+side,注意开闭区间
if (y <= -x + side and y <= x):
x += 1
elif(-x + side < y and y < x):
y += 1
elif(x<=y and -x + side < y):
x -= 1
elif(x<y and y<=-x+side):
y -= 1
# print(spiralMatrix)
for row in spiralMatrix:
print("t".join(map(lambda x:str(x), row)))
# num = int(input())
# num = input()
# a, b = num.split(" ")
# a = int(a)
# b = int(b)
# num = a + b
# interSpiralMatrix(num**2, a, b)
interSpiralMatrix(5)
结果:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
[Finished in 0.1s]
最后
以上就是舒心过客最近收集整理的关于回旋矩阵 - 由内到外 python实现的全部内容,更多相关回旋矩阵内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复