📅  最后修改于: 2023-12-03 15:36:22.942000             🧑  作者: Mango
在实际编程中,我们有时需要以特定的方式遍历矩阵,例如按照螺旋形式对角打印矩阵元素。本文将介绍如何实现这一功能。
首先我们来看一个简单的 4x4 矩阵:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
我们希望按照螺旋形式对角打印矩阵元素,其输出应为:
1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16
我们可以将其看做是从左上角开始,向右、向下、向左和向上遍历矩阵,每次遍历完一行或一列,就缩小遍历的范围,继续遍历剩下的部分。
具体来说,我们可以设置四个变量 top, bottom, left, right
来表示当前需要遍历的矩阵范围:
top
: 当前需要遍历的最上面一行的行索引;bottom
: 当前需要遍历的最下面一行的行索引;left
: 当前需要遍历的最左边一列的列索引;right
: 当前需要遍历的最右边一列的列索引。初始时,我们将 top
设为 0,bottom
设为 n-1
(其中 n
是矩阵的行数或列数,因为这是一个正方形矩阵,所以行列数相等),left
设为 0,right
设为 n-1
。
然后我们进行如下操作:
(top, left)
到 (top, right)
这一行上的所有元素。遍历完这一行后,将 top
加 1,这样下次遍历时就不会再遍历这一行了。(top+1, right)
到 (bottom, right)
这一列上的所有元素。遍历完这一列后,将 right
减 1,这样下次遍历时就不会再遍历这一列了。top
小于等于 bottom
,则从右往左遍历矩阵的最下面一行,即遍历 (bottom, right-1)
到 (bottom, left)
这一行上的所有元素。遍历完这一行后,将 bottom
减 1,这样下次遍历时就不会再遍历这一行了。left
小于等于 right
,则从下往上遍历矩阵的最左边一列,即遍历 (bottom-1, left)
到 (top+1, left)
这一列上的所有元素。遍历完这一列后,将 left
加 1,这样下次遍历时就不会再遍历这一列了。下面是基于上述思路实现的 Python 代码:
def spiralOrder(matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
result = []
if not matrix:
return result
m, n = len(matrix), len(matrix[0])
top, bottom, left, right = 0, m-1, 0, n-1
while top <= bottom and left <= right:
for j in range(left, right+1):
result.append(matrix[top][j])
top += 1
if top > bottom:
break
for i in range(top, bottom+1):
result.append(matrix[i][right])
right -= 1
if left > right:
break
for j in range(right, left-1, -1):
result.append(matrix[bottom][j])
bottom -= 1
if top > bottom:
break
for i in range(bottom, top-1, -1):
result.append(matrix[i][left])
left += 1
if left > right:
break
return result