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)
python 复制代码
# 输出数据
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])
相关推荐
_.Switch1 分钟前
Python Web 开发中的性能优化策略(一)
开发语言·前端·python·性能优化·django·flask·fastapi
零澪灵19 分钟前
ChartLlama: A Multimodal LLM for Chart Understanding and Generation论文阅读
论文阅读·python·自然语言处理·数据分析·nlp
程序员小王꧔ꦿ36 分钟前
python植物大战僵尸项目源码【免费】
python·游戏
拓端研究室TRL37 分钟前
Python用TOPSIS熵权法重构粮食系统及期刊指标权重多属性决策MCDM研究|附数据代码...
开发语言·python·重构
吃面不喝汤662 小时前
Flask + Swagger 完整指南:从安装到配置和注释
后端·python·flask
AI原吾6 小时前
掌握Python-uinput:打造你的输入设备控制大师
开发语言·python·apython-uinput
毕设木哥6 小时前
25届计算机专业毕设选题推荐-基于python的二手电子设备交易平台【源码+文档+讲解】
开发语言·python·计算机·django·毕业设计·课程设计·毕设
weixin_455446176 小时前
Python学习的主要知识框架
开发语言·python·学习
D11_7 小时前
Pandas缺失值处理
python·机器学习·数据分析·numpy·pandas