腾讯16-螺旋矩阵leetcode54
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
思路就是暴力,
但是写出逻辑清晰的暴力,还是很不容易,关键是用python的range在边界容易出错,最好不用for的range,都用while
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if len(matrix)==0 or len(matrix[0])==0:
return []
else:
#虽然是暴力,但是有逻辑的写出暴力也不容易
row_begin,col_begin=0,0
row_end,col_end=len(matrix)-1,len(matrix[0])-1
res=[]
while(row_begin<=row_end and col_begin<=col_end):
for i in range(col_begin,col_end+1):#[col_begin,col_end】从col_begin取到col_end
res.append(matrix[row_begin][i])
row_begin+=1
for i in range(row_begin,row_end+1):
res.append(matrix[i][col_end])
col_end-=1
if(row_begin<=row_end ):
for i in range(col_end,col_begin-1,-1):#[col_begin,col_end】从col_begin取到col_end
res.append(matrix[row_end][i])
row_end-=1
if(col_begin<=col_end ):
for i in range(row_end,row_begin-1,-1):#[col_begin,col_end】从col_begin取到col_end
res.append(matrix[i][col_begin])
col_begin+=1
return res