题目描述
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
示例1
输入:[[1,2,3],[4,5,6],[7,8,9]]
返回值:[1,2,3,6,9,8,7,4,5]
解题思路:注意边界问题
#
#
# @param matrix int整型二维数组
# @return int整型一维数组
#
class Solution:
def spiralOrder(self , matrix ):
# write code here
if not matrix:
return []
res = []
left,right,top,bottom = 0, len(matrix[0])-1, 0, len(matrix)-1
while left <= right and top <= bottom:
for i in range(left, right + 1):
res.append(matrix[top][i])
top = top + 1
for j in range(top, bottom+1):
res.append(matrix[j][right])
right -= 1
if top <= bottom:
for m in range(right, left-1, -1):
res.append(matrix[bottom][m])
bottom -= 1
if left <= right:
for n in range(bottom, top-1, -1):
res.append(matrix[n][left])
left += 1
return res