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])
相关推荐
小江的记录本1 天前
【JVM虚拟机】垃圾回收GC:四种引用类型:强引用、软引用、弱引用、虚引用(附《思维导图》+《面试高频考点清单》)
java·jvm·spring boot·后端·python·spring·面试
APIshop1 天前
Python 获取 1688 商品采集 API 接口 | 工厂货源自动化对接商品信息 | 无需选品
运维·python·自动化
deepin_sir1 天前
10 - 函数
开发语言·python
charlee441 天前
《GIS基础原理与技术实践》配套案例(Python版)
python·conda·numpy·gis·环境配置
枫叶林FYL1 天前
项目十:事件溯源仓储管理系统(WMS)仿真实现
开发语言·python
渣渣xiong1 天前
从零开始:前端转型AI agent直到就业第五十七天-第五十八天
前端·人工智能·python
小L~~~1 天前
基于贪心策略的混合遗传算法求解01背包问题
python·算法
才兄说1 天前
机器人二次开发机器人动作定制?动作迁移数据优化
python
用户8356290780511 天前
用 Python 实现 Excel 散点图绘制与定制
后端·python
PAK向日葵1 天前
从零实现 Python 虚拟机(一):PVM 基本原理介绍
python