题解 | #顺时针打印矩阵#

顺时针打印矩阵

https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        res = []
        n = len(matrix)
        if n==0:
            return res
        left = 0
        right = len(matrix[0])-1
        top = 0
        bottom = n-1
        while left<=right and top <=bottom:
            # 上边界从左到右
            for i in range(left,right+1):
                res.append(matrix[top][i])
            # 上边界向下
            top+=1
            if top>bottom:
                break
            # 右边界从上到下
            for i in range(top,bottom+1):
                res.append(matrix[i][right])
            # 右边界向左
            right -=1
            if right < left:
                break
            for i in range(right,left-1,-1):
                res.append(matrix[bottom][i])
            # 下边界向上
            bottom-=1
            if bottom<top:
                break
            # 左边界从下到上
            for i in range(bottom,top-1,-1):
                res.append(matrix[i][left])
            left +=1
            if left>right:
                break
        return res


            

                

全部评论

相关推荐

10-14 14:12
已编辑
少儿频道 算法工程师
反向练手了属于是
牛客71321951号:秋招的每一步都在成为小丑王的路上狂奔
点赞 评论 收藏
分享
我已成为0offer的糕手:羊毛出在羊身上罢了,当然,更多公司羊毛都不给你薅
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务