Easy to understanding python 44ms


  • 1
    L

    The idea is simple, just need to set left,right,up and bottom value of current matrix and add the elements from the margin and do the same with the inner matrix in the next loop. left == right or up == bottom means only 1 line left, so add them to the result list and break the loop.

    class Solution:
        #@param {integer[][]} matrix
        #@return {integer[]}
        def spiralOrder(self, matrix):
            if not matrix:
                return []
            left = up = 0
            right = len(matrix[0]) - 1
            bottom = len(matrix) - 1
            ret = []
            while left <= right and up <= bottom:
                if left == right:
                    for i in range(up,bottom+1):
                        ret.append(matrix[i][left])
                    break
                if up == bottom:
                    for i in range(left,right+1):
                        ret.append(matrix[bottom][i])
                    break
                for i in range(left, right+1):
                    ret.append(matrix[up][i])
                for i in range(up+1, bottom+1):
                    ret.append(matrix[i][right])
                for i in reversed(range(left, right)):
                    ret.append(matrix[bottom][i])
                for i in reversed(range(up+1,bottom)):
                    ret.append(matrix[i][left])
                up += 1
                right -= 1
                bottom -= 1
                left += 1
            return ret

Log in to reply
 

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