给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
LeetCode 链接
思路:
class Solution:
def spiralOrder(self, matrix):
if not matrix:
return None
m, n = len(matrix), len(matrix[0])
# 顺时针方向(右下左上)
dm = [0, 1, 0, -1]
dn = [1, 0, -1, 0]
di = 0 # 方向指针
res = []
x = y = 0 # 位置
for _ in range(m*n): # 最多步长 m*n
res.append(matrix[x][y])
matrix[x][y] = 'v' # 访问过标记为 'v'(‘visited’)
# 下一步位置
x_temp = x + dm[di]
y_temp = y + dn[di]
# 判断下一步位置是否合理,若合理则更新位置,若不合理则改变方向并更新位置
if 0<=x_temp<m and 0<=y_temp<n and matrix[x_temp][y_temp]!='v':
x, y = x_temp, y_temp
else:
di = (di+1) % 4
x += dm[di]
y += dn[di]
return res
test = Solution()
matrix_li = [
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
],
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
],
]
for matrix in matrix_li:
print(test.spiralOrder(matrix))
[1, 2, 3, 6, 9, 8, 7, 4, 5]
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]