【leetcode100】螺旋矩阵
1、题目描述
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
2、初始思路
2.1 思路
定义上下左右边界,从而循环输出。
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
m, n = len(matrix), len(matrix[0])
top, bottom, left, right = 0, m-1, 0, n-1
result = []
""" for i in range(2,2):
print(i) """
while top <= bottom and left <= right:
for i in range(left, right+1):
result.append(matrix[top][i])
top += 1
for j in range(top, bottom+1):
result.append(matrix[j][right])
right -= 1
if top <= bottom:
for k in range(right, left-1, -1):
result.append(matrix[bottom][k])
bottom -= 1
if left <= right:
for l in range(bottom, top-1, -1):
result.append(matrix[l][left])
left += 1
return result
3 总结
1、range循环的输出:
for i in range(2,2):
print(i)
#输出为null