Problem: Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

Solution: Spiral Matrix, Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-02-02 11:17:00
# @Author : NSSimacer
# @Version : 1.0
class Solution:
# @param matrix, a list of lists of integers
# @return a list of integers
def spiralOrder(self, matrix):
result = []
while matrix:
# Traverse Right
result += matrix.pop(0)
# Traverse Down
if matrix and matrix[0]:
for row in matrix:
result.append(row.pop())
# Traverse Left
if matrix:
result += matrix.pop()[::-1]
# Traverse Up
if matrix and matrix[0]:
for row in matrix[::-1]:
result.append(row.pop(0))
return result

时间复杂度O(N2),空间复杂度O(1)。