码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Spiral Matrix

时间:2018-04-23 22:41:17      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:==   lis   pytho   markdown   个数   range   pretty   AC   控制   

LeetCode解题之Spiral Matrix


原题

将一个矩阵中的内容螺旋输出。

注意点:

  • 矩阵不一定是正方形

样例:

输入: matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

输出: [1, 2, 3, 6, 9, 8, 7, 4, 5]

解题思路

控制好当前遍历的边界,不断的向内缩进。

须要注意的是,缩到最里面的时候可能会出现下面几种情况:

中心剩下一个数值
———
|3|
———

中心横向多个数值
—————————
|3 4 5 6|
—————————

中心纵向多个数值
———
|2|
|3|
|4|
———

分别处理一下就可以。

AC源代码

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if not matrix:
            return []
        left = top = 0
        right = len(matrix[0]) - 1
        bottom = len(matrix) - 1

        result = []
        while left < right and top < bottom:
            for i in range(left, right):
                result.append(matrix[top][i])
            for i in range(top, bottom):
                result.append(matrix[i][right])
            for i in range(right, left, -1):
                result.append(matrix[bottom][i])
            for i in range(bottom, top, -1):
                result.append(matrix[i][left])
            left += 1
            right -= 1
            top += 1
            bottom -= 1
        if left == right and top == bottom:
            result.append(matrix[top][left])
        elif left == right:
            for i in range(top, bottom + 1):
                result.append(matrix[i][left])
        elif top == bottom:
            for i in range(left, right + 1):
                result.append(matrix[top][i])
        return result


if __name__ == "__main__":
    assert Solution().spiralOrder([
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]) == [1, 2, 3, 6, 9, 8, 7, 4, 5]
    assert Solution().spiralOrder([[2], [3]]) == [2, 3]
    assert Solution().spiralOrder([[2, 3]]) == [2, 3]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

LeetCode Spiral Matrix

标签:==   lis   pytho   markdown   个数   range   pretty   AC   控制   

原文地址:https://www.cnblogs.com/zhchoutai/p/8921940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!