前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >打卡群刷题总结0710—— 螺旋矩阵

打卡群刷题总结0710—— 螺旋矩阵

作者头像
木又AI帮
发布2020-07-16 15:04:05
2500
发布2020-07-16 15:04:05
举报
文章被收录于专栏:木又AI帮

题目:54. 螺旋矩阵

链接:https://leetcode-cn.com/problems/spiral-matrix

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 示例 1: 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5] 示例 2: 输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]

解题:

1、直接暴力破解即可,注意边界条件。

代码:

代码语言:javascript
复制
class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if len(matrix) == 0:
            return []
        if len(matrix) == 1:
            return matrix[0]

        top, bottom = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1
        res = []
        while top <= bottom and left <= right:
            if top <= bottom:
                # top:left->right
                for j in range(left, right + 1):
                    res.append(matrix[top][j])
                top += 1
            if left <= right:
                # right: top -> bottom
                for i in range(top, bottom + 1):
                    res.append(matrix[i][right])
                right -= 1
            if top <= bottom:
                # bottom: right -> left
                for j in range(right, left - 1, -1):
                    res.append(matrix[bottom][j])
                bottom -= 1
            if left <= right:
                # left: bottom -> top
                for i in range(bottom, top - 1, -1):
                    res.append(matrix[i][left])
                left += 1
        return res
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-07-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档