Python刷题日记--回形取数

基础练习 回形取数
时间限制:1.0s   内存限制:512.0MB
问题描述  回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。输入格式  输入第一行是两个不超过200的正整数m, n,表示矩阵的行和列。接下来m行每行n个整数,表示这个矩阵。输出格式  输出只有一行,共mn个数,为输入矩阵回形取数得到的结果。数之间用一个空格分隔,行末不要有多余的空格。样例输入3 3
1 2 3
4 5 6
7 8 9样例输出1 4 7 8 9 6 3 2 5样例输入3 2
1 2
3 4
5 6样例输出1 3 5 6 4 2

left_min = 0
right_max = 0
up_min = 0
down_max = 0


def down(arr, l):
    global left_min
    if left_min == right_max or up_min == down_max:
        return

    for j in range(up_min, down_max):
        print(arr[j][l], end=" ")
    left_min += 1
    right(arr, down_max - 1)


def right(arr, h):
    global down_max
    if left_min == right_max or up_min == down_max:
        return

    for j in range(left_min, right_max):
        print(arr[h][j], end=" ")
    down_max -= 1
    up(arr, right_max - 1)


def up(arr, l):
    global right_max
    if left_min == right_max or up_min == down_max:
        return

    for j in range(down_max - 1, up_min - 1, -1):
        print(arr[j][l], end=" ")
    right_max -= 1
    left(arr, up_min)


def left(arr, h):
    global up_min
    if left_min == right_max or up_min == down_max:
        return

    for j in range(right_max - 1, left_min - 1, -1):
        print(arr[h][j], end=" ")
    up_min += 1
    down(arr, left_min)


if __name__ == "__main__":
    h, l = [int(i) for i in input().split()]
    right_max = l
    down_max = h
    arr = [[int(i) for i in input().split()] for _ in range(h)]
    down(arr, 0)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
蓝桥杯是中国最具影响力的计算机竞赛之一,回形取数是蓝桥杯中的一道经典题目。下面是关于Python实现回形取数的介绍: 回形取数是指从一个矩阵中按照回形的方式依次取出所有的元素。具体来说,就是从矩阵的左上角开始,按照顺时针的方向依次取出元素,直到取完所有元素为止。 在Python中,可以通过嵌套列表来表示矩阵。下面是一个示例代码,实现了回形取数的功能: ```python def spiral_order(matrix): if not matrix: return [] rows, cols = len(matrix), len(matrix[0]) top, bottom, left, right = 0, rows - 1, 0, cols - 1 result = [] while top <= bottom and left <= right: # 从左到右 for col in range(left, right + 1): result.append(matrix[top][col]) top += 1 # 从上到下 for row in range(top, bottom + 1): result.append(matrix[row][right]) right -= 1 if top <= bottom: # 从右到左 for col in range(right, left - 1, -1): result.append(matrix[bottom][col]) bottom -= 1 if left <= right: # 从下到上 for row in range(bottom, top - 1, -1): result.append(matrix[row][left]) left += 1 return result # 测试 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] result = spiral_order(matrix) print(result) ``` 以上代码中,`spiral_order`函数接受一个二维列表作为输入,表示矩阵。函数通过设定上下左右四个边界来控制取数的范围,然后按照顺时针的方向依次取出元素,并将其添加到结果列表中。最后返回结果列表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

quzah

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

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

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

打赏作者

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

抵扣说明:

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

余额充值