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])

相关推荐

  1. OD C - 螺旋数组矩阵

    2024-03-31 14:40:08       42 阅读
  2. 华为OD机试-螺旋数字矩阵

    2024-03-31 14:40:08       38 阅读
  3. 1130. 【二维数组】打印螺旋矩阵

    2024-03-31 14:40:08       29 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-31 14:40:08       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-31 14:40:08       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-31 14:40:08       82 阅读
  4. Python语言-面向对象

    2024-03-31 14:40:08       91 阅读

热门阅读

  1. Clickhouse 查看分区情况

    2024-03-31 14:40:08       46 阅读
  2. centos7.5 安装gitlab-ce (Omnibus)

    2024-03-31 14:40:08       40 阅读
  3. 【Go】goroutine并发常见的变量覆盖案例

    2024-03-31 14:40:08       40 阅读
  4. Vue的侦听方法和生命周期

    2024-03-31 14:40:08       41 阅读
  5. Viso的使用

    2024-03-31 14:40:08       57 阅读
  6. LeetCode 84. 柱状图中最大的矩形

    2024-03-31 14:40:08       34 阅读
  7. 【BlossomRPC】一个完整的含源码和文档的RPC项目

    2024-03-31 14:40:08       35 阅读
  8. 补关于zip安装mysql-8.0版本问题

    2024-03-31 14:40:08       39 阅读