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]
这道题目的意思是把矩阵螺旋的顺序排出来,但从难度来看,是毫无难度的,但写起来发现还是比较麻烦的。
Python解法如下:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix: return []
R, C = len(matrix), len(matrix[0])
seen = [[False] * C for _ in matrix]
ans = []
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
r = c = di = 0
for _ in range(R * C):
ans.append(matrix[r][c])
seen[r][c] = True
cr, cc = r + dr[di], c + dc[di]
if 0 <= cr < R and 0 <= cc < C and not seen[cr][cc]:
r, c = cr, cc
else:
di = (di + 1) % 4
r, c = r + dr[di], c + dc[di]
return ans
看到另外一个逻辑更清晰的代码:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
if len(matrix)==0:
return res
m = len(matrix)
n = len(matrix[0])
k = 0
l = 0
last_row = m-1
last_col = n-1
while k <= last_row and l <= last_col:
for i in range(l,last_col+1):
res.append(matrix[k][i])
k += 1
for i in range(k,last_row+1):
res.append(matrix[i][last_col])
last_col -= 1
if(k<=last_row):
for i in range(last_col,l-1,-1):
res.append(matrix[last_row][i])
last_row -= 1
if(l<=last_col):
for i in range(last_row,k-1,-1):
res.append(matrix[i][l])
l += 1
return res

本文解析了LeetCode上的螺旋矩阵题目,提供了两种Python实现方案,一种使用方向数组模拟螺旋移动,另一种通过边界循环实现,详细阐述了算法思路与代码实现。
1892

被折叠的 条评论
为什么被折叠?



