美文网首页
Spiral Matrix

Spiral Matrix

作者: 穿越那片海 | 来源:发表于2017-08-14 21:08 被阅读0次

    Easy, Msc

    Question

    返回一个m x n的矩阵的螺旋序列

    For example,
    矩阵:
    [
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
    ]
    的螺旋序列是[1,2,3,6,9,8,7,4,5].

    Solution

    螺旋序列的直观表示如下图


    Screen Shot 2017-08-14 at 8.55.29 PM.jpg

    直观答案如下

    class Solution(object):
        def spiralOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
            ret = []
            if len(matrix) == 0: return ret
            
            m, n = len(matrix), len(matrix[0])
            row, col = 0, -1
            while True:
                for i in xrange(n):
                    col += 1
                    ret.append(matrix[row][col])
                m -= 1
                if m == 0: break
                    
                for i in xrange(m):
                    row += 1
                    ret.append(matrix[row][col])
                n -= 1
                if n == 0: break
                    
                for i in xrange(n):
                    col -= 1
                    ret.append(matrix[row][col])
                m -= 1
                if m == 0: break
                    
                for i in xrange(m):
                    row -= 1
                    ret.append(matrix[row][col])
                n -= 1
                if n == 0: break
                    
            return ret       
    

    更加简洁的写法

    class Solution(object):
        def spiralOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
            ret = []
            if len(matrix) == 0:
                return ret
            while matrix:
                ret += matrix.pop(0)
                if matrix and matrix[0]:
                    for row in matrix:
                        ret.append(row.pop())
                if matrix:
                    ret += matrix.pop()[::-1]
                if matrix and matrix[0]:
                    for row in matrix[::-1]:
                        ret.append(row.pop(0))
            return ret
    

    最后献上StefanPochmann 大神的神解法, 真正让矩阵旋转起来。

    def spiralOrder(self, matrix):
        return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1])
    

    相关文章

      网友评论

          本文标题:Spiral Matrix

          本文链接:https://www.haomeiwen.com/subject/ecdprxtx.html