题解 | #螺旋矩阵#

螺旋矩阵

https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

#coding:utf-8
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param matrix int整型二维数组 
# @return int整型一维数组
#
class Solution:
    def spiralOrder(self , matrix ):
        # write code here
        if matrix == []:
            return []
        res = []
        left = 0
        top = 0
        bottom = len(matrix) - 1
        right = len(matrix[0]) - 1

        while len(res) < (len(matrix) * len(matrix[0])):

            for j in range(left, right + 1):
                res.append(matrix[top][j])
            top += 1

            for i in range(top, bottom + 1):
                res.append(matrix[i][right])
            right -= 1

            for j in range(right, left - 1, -1):
                if top - 1 == bottom:
                    break
                res.append(matrix[bottom][j])
            bottom -= 1

            for i in range(bottom, top - 1, -1):
                if left - 1 == right:
                    break
                res.append(matrix[i][left])
            left += 1

        return res

设置上下左右四个边界,后面两次需要增加上下和左右是否相等的判断(否则会重复)。开头增加特殊情况判断。

全部评论

相关推荐

05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
投递长鑫存储等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务