原题
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
解法1
按行或者按列从matrix中提取数字并将数字放入res中, 每次放入之前要检查matrix是否为空或者行数是否为0.
代码
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
res = []
while matrix:
# add the first row
res += matrix.pop(0)
# add the right-most col
if matrix and matrix[0]:
for row in matrix:
res.append(row.pop())
# add the bottom row from right to left
if matrix:
res += matrix.pop()[::-1]
# add the left-most col from bottom to up
if matrix and matrix[0]:
res += [row.pop(0) for row in matrix][::-1]
return res
解法2
设定4个方向: 右/下/左/上, 初始化x,y坐标和方向, 将matrix的值依次放入ans里, 并将已读取过的值设为’#’.
代码
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix: return []
directions = [(0,1),(1,0),(0,-1),(-1,0)]
index = 0
ans = []
x,y = 0, 0
m, n = len(matrix), len(matrix[0])
for i in range(m*n):
ans.append(matrix[x][y])
matrix[x][y] = '#'
dx, dy = directions[index][0],directions[index][1]
if 0 <= x+dx < m and 0<= y+dy < n and matrix[x+dx][y+dy] != "#":
x = x+dx
y = y+dy
else:
index = (index+1)%4
dx, dy = directions[index][0],directions[index][1]
x = x+dx
y = y+dy
return ans