Given a matrix ofmn elements (mrows, n columns), return all elements of the matrix in spiral order.
For example, Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
For example, Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
invariant: 任何时候都对应一个当前有效的上、下、左、右的界。 在当前上、下、左、右界内依次输出每条边,同时更新相应的界,如果上下界或者左右界交错,算法结束。
def spiralOrder(matrix):
res = []
startX, endX, startY, endY = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
while True:
for j in xrange(startX, endX + 1):
res.append(matrix[startY][j])
startY += 1
if startY > endY: break
for i in xrange(startY, endY + 1):
res.append(matrix[i][endX])
endX -= 1
if startX > endX: break
for j in xrange(endX, startX - 1, -1):
res.append(matrix[endY][j])
endY -= 1
if startY > endY: break
for i in xrange(endY, startY - 1, -1):
res.append(matrix[i][startX])
startX += 1
if startX > endX: break
return res;

本文介绍了一种矩阵螺旋遍历的算法实现,该算法能够按螺旋顺序返回矩阵的所有元素。通过定义上下左右边界并逐步更新边界值的方式,实现了对矩阵元素的有效遍历。
398

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



