OD C卷 - 螺旋数组矩阵

螺旋数组矩阵(100)

  • 给出数字的个数n, 行数m, (1 < n,m < 999)
  • 从左上角的1开始,按照顺时针螺旋向内写方式,依次写出2,3,…n,最终形成一个m行矩阵;
  • 每行数字的个数一样多,且列数尽可能少,数字不够时,使用*占位;
    输入描述:
    n m
    输出描述:
    符合要求的唯一矩阵

示例1
输入:
9 4
输出:
1 2 3
*  *  4
9 * 5
8 7 6

示例2
输入:
3 5
输出
1
2
3
*
*
思路:

  • 控制写数字的方向 [0, 1, 0, -1, 0],每次取两个值,分别控制行、列的行走;
  • 列数最少为 math.ceil(n/m)

# 输出数据
n, row = list(map(int, input().strip().split()))
# 计算最少的列
col = n // row if n % row == 0 else n // row + 1

# 初始化 matrix 矩阵
matrix = [["*" for j in range(col)] for i in range(row)]

# 控制方向的关键
direct = [0, 1, 0, -1, 0]

# 螺旋写数字
k = 1
index = 0
start_x = 0
start_y = 0
while True:
    if k > n:
        break
    else:
        matrix[start_x][start_y] = k
        k += 1
        # 计算新位置
        new_x = start_x + direct[index]
        new_y = start_y + direct[index + 1]

        # 位置有效
        if 0 <= new_x < row and 0 <= new_y < col and matrix[new_x][new_y] == "*":
            # 可以写数字
            start_x = new_x
            start_y = new_y
        else:
            # 调转方向
            index = (index + 1) % 4
            start_x = start_x + direct[index]
            start_y = start_y + direct[index + 1]

# 输出结果
for i in range(row):
    output = ""
    for j in range(col):
        output += str(matrix[i][j]) + " "
    print(output[:-1])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laufing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值