7 lines, recursive python solution (+ 5 lines solution w/o recursion)


  • 8
    O

    (1). Initial

    1, 2, 3

    4, 5, 6

    7, 8, 9

    (2). The first row, [1, 2, 3], is used

    4, 5, 6

    7, 8, 9

    (3). Rotate the rest into:

    6, 9

    5, 8

    4, 7

    (4). Use the first row after rotation. Got [1, 2, 3, 6, 9, ... ] and just keep going !

    def spiralOrder(self, matrix):
    
        result = []
    
        def helper(mat):
            if mat:
                result.extend(mat[0])
                helper(self.rotate_counter(mat[1:]))
    
        helper(matrix)
        return result
    
    def rotate_counter(self, mat):
        return zip(*mat)[::-1]
    

    p.s. I isolate the rotation function for readability.
    p.s. fixed the redundancy & added a while-loop version under the suggestion of StefanPochmann

    def spiralOrder(self, matrix):    #a while-loop version
    
        result = []
    
        while matrix:
            result.extend(matrix.pop(0))
            matrix = zip(*matrix)[::-1]    #rotate the remaining matrix counter-clockwise
            
        return result

  • 0

    I don't think the recursion really helps here. Try a while loop, that's shorter and simpler.


  • 0
    O

    Thanks for the useful suggestion.


  • 0

    You're welcome. One little "trick" you could still use is result += matrix.pop(0), which does the same as your result.extend(matrix.pop(0)). Unlike +, the += allows a tuple to be added to a list.


  • 1
    B

    this is the most elegant solution I ever seen for this question. Good Job man!


Log in to reply
 

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