Short concise python solution (14lines)


  • 2
    G
    class Solution:
        def spiralOrder(self, matrix):
            spiral = []
            try:
                while True:
                    spiral += matrix.pop(0)
                    for i in range(len(matrix)):
                        spiral.append(matrix[i].pop(-1))
                    spiral += reversed(matrix.pop(-1))
                    for i in range(len(matrix)):
                        spiral.append(matrix[len(matrix) - 1 - i].pop(0))
            except:
                pass
            return spiral
    

    Basicly, eat the top line, right line, bottom, then left, loop


  • 0
    A

    Can 14 lines be short ?

    Stefan have a ONE line solution in Python. How about his solution ?


  • 0

    Mine is less efficient. For what it's doing, this one is fairly short.

    And this was posted before mine. Check the dates.

    And it's not 14 lines but 12 lines (or else you should count mine as 3, not 1).

    I'd just change it to this:

    def spiralOrder(self, matrix):
        spiral = []
        try:
            while True:
                spiral += matrix.pop(0)
                spiral += map(list.pop, matrix)
                spiral += reversed(matrix.pop())
                spiral += [row.pop(0) for row in reversed(matrix)]
        except:
            return spiral

  • 0

    And now I posted a Ruby 1-liner so I could ask the same about your "concise" Ruby 7-liner :-P


Log in to reply
 

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