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])
相关推荐
曲幽5 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805110 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon11 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly11 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程11 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly13 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风20 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风20 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python