10 lines Python easy to implement


  • 2
    class Solution(object):
        def spiralOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
            if len(matrix) == 0 or len(matrix[0]) == 0:
                return []
            ans = []
            left, up, bottom, right = 0, 0, len(matrix) - 1, len(matrix[0]) - 1
            while left <= right and up <= bottom:
                ans, up = ans + [matrix[up][j] for j in range(left, right + 1)], up + 1
                ans, right = ans + [matrix[i][right] for i in range(up, bottom + 1)], right - 1
                ans, bottom = ans + [matrix[bottom][j] for j in reversed(xrange(left, right + 1))], bottom - 1
                ans, left = ans + [matrix[i][left] for i in reversed(xrange(up, bottom + 1))], left + 1
            return ans[:len(matrix) * len(matrix[0])]
    

Log in to reply
 

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