题目:
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例:
思路:
- 需要考虑的是旋转的方向和边界,设置左右上下边界,顺时针,右下左上四个方向,每个方向里表示的是这个方向移动时x和y坐标的移动。
- 初始化坐标(0,0),进入循环,将当前坐标的数加进结果中,然后根据当前方向调整x和y,当方向是右且到达右边界时,改变方法向下,上边界往下挪一个,当方向是下且到达下边界时,改变方法向左,右边界向左移动一位,当方向是左且到达左边界时,改变方法向上,下边界向上移动一位,当方向向上,到达上边界时,改变方法向右,左边界向右移动一位。直到遍历完整个矩阵,返回列表。
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
#注意起始位置,移动方向,边界条件,结束条件
res = []
if not matrix:return res
m = len(matrix)
n = len(matrix[0])
x,y = 0,0
left,right,top,down = 0,n-1,0,m-1
dir = [(0,1),(1,0),(0,-1),(-1,0)]
cur = 0
while len(res) != m*n:#注意这里是返回列表的长度
res.append(matrix[x][y])
if cur == 0 and y == right:
cur += 1
top += 1
elif cur == 1 and x == down:
cur += 1
right -= 1
elif cur == 2 and y == left:
cur += 1
down -= 1
elif cur == 3 and x ==top:
cur += 1
left += 1
cur %= 4
x += dir[cur][0]
y += dir[cur][1]
return res