Python HackerRank 刷题 Matrix Layer Rotation

题目地址: https://www.hackerrank.com/challenges/matrix-rotation-algo/problem?isFullScreen=false

翻译:将一个mXn的矩阵按步长r逆时针螺旋旋转。例子如下:

matrix-rotation

难度:Hard

解题

本来想找找有没有公式一步到位,然并没有找到。那只能一圈一圈拿出来了。本来想拿的时候能不能两个for嵌套完事,无奈能力有限,想了好久也没搞定。最后只能分上下左右4个循环整了。

import copy

def matrixRotation(matrix, r, m, n):
    # Write your code here
    layer = int(min(m,n) / 2)                        # 计算几个圈
    temp = [[] for i in range(layer)]                # 用来存圈

    # 四角指针
    r_top=0                                          
    r_bottom=m-1
    c_left=0
    c_right=n-1

    while (r_top <= r_bottom and c_left <= c_right):
        for i in range(c_left, c_right):            # 上
            temp[r_top].append(matrix[r_top][i])
        for i in range(r_top, r_bottom):            # 右
            temp[r_top].append(matrix[i][c_right])
        for i in range(c_right, c_left, -1):        # 下
            temp[r_top].append(matrix[r_bottom][i])
        for i in range(r_bottom, r_top, -1):        # 左
            temp[r_top].append(matrix[i][c_left])
        # 换圈
        r_top += 1
        r_bottom -= 1
        c_left += 1
        c_right -= 1
    
    rotat_temp = copy.deepcopy(temp)                # 深拷贝用来滑动
    for i in range(len(temp)):
        r_k = r % len(temp[i])
        for j in range(len(temp[i])):               # 滑起来
            rotat_temp[i][j] = temp[i][(j+r_k)%len(temp[i])]

    # 用来把圈还原成正常二维数组
    rt = [[0 for i in range((j-1)*n+1,n*j+1)] for j in range(1,m+1)]
    
    # 四神归位
    r_top=0
    r_bottom=m-1
    c_left=0
    c_right=n-1
    
    # 反向操作
    while (r_top <= r_bottom and c_left <= c_right):
        for i in range(c_left, c_right):        # top
            rt[r_top][i] = str(rotat_temp[r_top].pop(0))
        for i in range(r_top, r_bottom):        # right
            rt[i][c_right] = str(rotat_temp[r_top].pop(0))
        for i in range(c_right, c_left, -1):    # bottom
            rt[r_bottom][i] = str(rotat_temp[r_top].pop(0))
        for i in range(r_bottom, r_top, -1):    # left
            rt[i][c_left] = str(rotat_temp[r_top].pop(0))
        r_top += 1
        r_bottom -= 1
        c_left += 1
        c_right -= 1
    
    # 打印收工
    for i in rt:
        print(' '.join(i))

这么搞居然可以通过所有case。那么问题来了,究竟能不能少点循环呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值