Simple Python solution by mutating the matrix


  • 32
    C

    The con is mutating the matrix, if this is not allowed, we can make a deep copy of the matrix first. And of course it comes with the additional memory usage.

    def spiralOrder(self, matrix):
        ret = []
        while matrix:
            ret += matrix.pop(0)
            if matrix and matrix[0]:
                for row in matrix:
                    ret.append(row.pop())
            if matrix:
                ret += matrix.pop()[::-1]
            if matrix and matrix[0]:
                for row in matrix[::-1]:
                    ret.append(row.pop(0))
        return ret

  • 0
    L

    really a smart idea!


  • 0
    F

    Interesting idea, but the running time will be larger than O(mn), since the last case, which is

            for row in matrix[::-1]:
                ret.append(row.pop(0))
    

    needs O(mn) for each stage and there are O(min(m, n)) stages.

    Of course, you may use collections.deque to remedy that.


  • 0
    W

    neat solution without using recursion


  • 0
    N
    This post is deleted!

  • 0
    T

    python solution without using recursion too.

    def spiralOrder(self, matrix):
            if len(matrix) == 0: return []
            M, N, result = len(matrix), len(matrix[0]), []
            CN = min(M, N)/2
            for i in xrange(CN):
                result += matrix[i][i:~i]
                result += [arow[~i] for arow in matrix[i:~i]]
                result += matrix[~i][::-1][i:~i]
                result += [arow[i] for arow in matrix[::-1][i:~i]]
            if M > N and N % 2 == 1: result += [arow[N/2] for arow in matrix[CN:M-CN]]
            elif N >= M and M % 2 == 1: result += matrix[M/2][CN:N-CN]
            return result

  • 0
    Z

    遍历的过程中进行了裁剪,真是特别棒的方法


  • 0

    @tju_xu97 what does ~ mean?


  • 0
    W

    smart solution!


  • 0
    N

    @ChuntaoLu It is a good idea, very well in use python feature, thank you


Log in to reply
 

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