Python solution, easy to understand


  • 0
    K

    Coordinate (0, 0) is matrix[0][0], x-axis is the first row from left to right, y-axis is the first column from top to bottom. dx, dy = -dy, dx means turning right.

    def spiralOrder(self, matrix):
        if not matrix: return []
        rows, cols, result = len(matrix), len(matrix[0]), []
        N, x, y, dx, dy = rows * cols, -1, 0, 1, 0
        while True:
            for i in xrange(cols):
                x, y = x + dx, y + dy
                result += matrix[y][x],
            rows -= 1
            if not rows: return result
            dx, dy = -dy, dx
            for i in xrange(rows):
                x, y = x + dx, y + dy
                result += matrix[y][x],
            cols -= 1
            if not cols: return result
            dx, dy = -dy, dx

  • 0
    X

    Good solution. One comment. result is a list, but matrix[y][x] is a number. They can't be added together using '+=' operator. result.append(...) is necessary.


  • 0
    X

    wait.. You are using a comma in the end. That would work! Sorry~


  • 0
    K

    You are right. Next time I should use append() since it's faster.

    >>> import timeit
    >>> timeit.timeit(setup = 'res = []', stmt = 'for i in xrange(100): res += i,', number = 1000000)
    8.432456016540527
    >>> timeit.timeit(setup = 'res = []', stmt = 'for i in xrange(100): res.append(i)', number = 1000000)
    8.049201965332031

Log in to reply
 

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