题解 | #螺旋矩阵# | 二维转一维 | 螺旋方式展开

螺旋矩阵

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

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param matrix int整型二维数组
# @return int整型一维数组


class Solution:
    # 顺时针展开
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        m = len(matrix)
        if m <= 0:
            return res
        n = len(matrix[0])
        x1, x2, y1, y2 = 0, n, 0, m
        while x1 < x2 and y1 < y2:
            for i in range(x1, x2):
                res.append(matrix[y1][i])
            y1 += 1
            for j in range(y1, y2 - 1):
                res.append(matrix[j][x2 - 1])
            x2 -= 1
            if y1 == y2:  # 针对单行情况,不左行
                break
            for i in range(x2, x1 - 1, -1):
                res.append(matrix[y2 - 1][i])
            y2 -= 1
            if x1 == x2:  # 针对单列情况,不上行
                break
            for j in range(y2 - 1, y1 - 1, -1):
                res.append(matrix[j][x1])
            x1 += 1
        return res

    # # 逆时针展开
    # def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
    #     res = []
    #     m = len(matrix)
    #     if m <= 0:
    #         return res
    #     n = len(matrix[0])
    #     x1, x2, y1, y2 = 0, n, 0, m
    #     while x1 < x2 and y1 < y2:
    #         for j in range(y1, y2):
    #             res.append(matrix[j][x1])
    #         x1 += 1
    #         for i in range(x1, x2 - 1):
    #             res.append(matrix[y2 - 1][i])
    #         y2 -= 1
    #         if x1 == x2:  # 针对单列情况,不上行
    #             break
    #         for j in range(y2, y1 - 1, -1):
    #             res.append(matrix[j][x2 - 1])
    #         x2 -= 1
    #         if y1 == y2:  # 针对单行情况,不左行
    #             break
    #         for i in range(x2 - 1, x1 - 1, -1):
    #             res.append(matrix[y1][i])
    #         y1 += 1
    #     return res

全部评论

相关推荐

我已成为0offer的糕手:别惯着,胆子都是练出来的,这里认怂了,那以后被裁应届被拖工资还敢抗争?
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务