回旋矩阵 - 由内到外 python实现

简洁版:

# 由内到外输出数字矩阵
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]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值