An iterative Python solution


  • 3
    G

    The idea is to peel the the matrix layer by layer.

    class Solution:
        # @param matrix, a list of lists of integers
        # @return a list of integers
        # 9:27
        def spiralOrder(self, matrix):
            result = []
            
            while matrix and matrix[0]:
                if matrix[0]:
                    result += matrix.pop(0)
                
                if matrix and matrix[0]:
                    for row in matrix:
                        result.append(row.pop())
                
                if matrix and matrix[-1]:
                    result += matrix.pop()[::-1]
    
                if matrix and matrix[0]:
                    for row in matrix[::-1]:
                        result.append(row.pop(0))
            
            return result

  • 0
    C

    Nice solution!


  • 1
    C

    Nice idea, after carefully checking your code, it seems some "if checkings" are redundant, here is a new version:

    def spiralOrder(self, matrix):
        res = []
        while matrix:
            res.extend(matrix.pop(0)) # left to right
            if matrix and matrix[0]: # top to dwon
                for row in matrix:
                    res.append(row.pop())
            if matrix: # right to left
                res.extend(matrix.pop()[::-1])
            if matrix and matrix[0]: # bottom to up
                for row in matrix[::-1]:
                    res.append(row.pop(0))
        return res

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.