题解 | #螺旋矩阵#
螺旋矩阵
http://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
该方法主要是容易避免考虑太细的边界问题
每次走完当前边,然后将边界值缩小/扩大1。
然后判断边界是否遍历完,遍历完即退出循环
#
#
# @param matrix int整型二维数组
# @return int整型一维数组
#
class Solution:
def spiralOrder(self , matrix ):
# write code here
if len(matrix) < 1 or len(matrix[0]) < 1:
return []
ans = []
top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
while bottom >= top and left <= right:
for i in range(left, right + 1): # ->
ans.append(matrix[top][i])
top += 1
if top > bottom:
break
for i in range(top, bottom + 1): # down
ans.append(matrix[i][right])
right -= 1
if right < left:
break
for i in range(right, left - 1, -1):
ans.append(matrix[bottom][i])
bottom -= 1
if top > bottom :
break
for i in range(bottom, top - 1, -1):
ans.append(matrix[i][left])
left += 1
return ans
查看2道真题和解析
