给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
由于行列不相等,因此定义四个变量用于记录边界:
- 左边界left
- 右边界right
- 上边界top
- 下边界bottom
然后以top和left基准层层打印,值得注意的是,为了避免重复打印,我们需要在打印下边和左边时额外判断一下top和bottom以及left和right是否相等:
class Solution:
def spiralOrder(self , matrix ):
# write code here
res = []
if len(matrix) == 0:
return res
#定义四个指针,并且充当边界限制的作用
top = 0
bottom = len(matrix)-1
left = 0
right = len(matrix[0])-1
#range(left,right+1)即i=left;i<=right;i++
while top <= bottom and left <= right:
for i in range(left, right+1): #上面 左到右
res.append(matrix[top][i])
for i in range(top+1, bottom+1): #右边 上到下
res.append(matrix[i][right])
if top != bottom: #range(right-1, left-1,-1)即i=right-1;i>=left;i--
for i in range(right-1, left-1, -1):#下面 右到左
res.append(matrix[bottom][i])
if left != right:
for i in range(bottom-1, top, -1): #左边 下到上
res.append(matrix[i][left])
#遍历完一圈之后,所有往里面靠
top += 1
bottom -= 1
left += 1
right -= 1
return res