Coordinate (0, 0) is matrix, 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),  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
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.
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
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.