Not super concise, but very structured


  • 0
    D
    def spiralOrder(self, matrix):
        ans = []
        while matrix:
            matrix = self.right(matrix, ans)
            matrix = self.down(matrix, ans)
            matrix = self.left(matrix, ans)
            matrix = self.up(matrix, ans)
        return ans
            
    def right(self, matrix, ans):
        if not matrix: return []
        ans.extend(matrix[0])
        return matrix[1:]
        
    def down(self, matrix, ans):
        if not matrix: return []
        ans.extend([r[-1] for r in matrix])
        return [r[:-1] for r in matrix if r[:-1]]
        
    def left(self, matrix, ans):
        if not matrix: return []
        ans.extend(matrix[-1][::-1])
        return matrix[:-1]
        
    def up(self, matrix, ans):
        if not matrix: return []
        ans.extend([r[0] for r in matrix][::-1])
        return [r[1:] for r in matrix if r[1:]]

Log in to reply
 

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