54. Spiral Matrix
题目
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]
分析
难度不大的一道题,只要清楚遍历矩阵时每个方向都要遍历哪些元素即可(有一个坑就是要考虑到矩阵为空的情况)
设矩阵为m*n,易得:
初始时向右遍历,行标号不变,列标号范围为[0,n)
随后向下遍历,列标号不变,行标号范围为[1,m)
向左遍历,行标号不变,列标号范围为[0,n-1)
向上遍历,列标号不变,行标号范围为[1,m-1)
按一个方向遍历完后标号范围左右两边都要减一,考虑可读性,范围可以用字典存储
代码
if not matrix: return []
m, n = len(matrix), len(matrix[0])
direction = ['R', 'D', 'L', 'U']
pathRange = {
direction[0]: (0, n),
direction[1]: (1, m),
direction[2]: (0, n-1),
direction[3]: (1, m-1)
}
row, col, d, count, res = 0, 0, 0, 0, []
while count < m*n:
x, y = pathRange[direction[d]]
if direction[d] == 'R':
res.extend([matrix[row][i] for i in range(x, y)])
col = y-1
elif direction[d] == 'D':
res.extend([matrix[i][col] for i in range(x, y)])
row = y-1
elif direction[d] == 'L':
res.extend([matrix[row][i] for i in reversed(range(x, y))])
col = x
elif direction[d] == 'U':
res.extend([matrix[i][col] for i in reversed(range(x, y))])
row = x
count += y - x
pathRange[direction[d]] = x+1, y-1
d = (d+1) % 4
return res