Leetcode54-螺旋矩阵
思路:
依次向右向下向左向上遍历。
使用while来控制循环:
while(true)作为无限循环,经常在不知道循环次数的时候使用,并且需要在循环内使用break才会停止。
break条件:left>right or top>botton
代码:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
left, right = 0, len(matrix[0]) - 1
top, botton = 0, len(matrix) - 1
res = []
while True: #不知道循环次数的时候使用
for i in range(left, right + 1):
#向右遍历
res.append(matrix[top][i])
top += 1 #下一行
if top > botton:
break
for i in range(top, botton + 1):
#向下遍历
res.append(matrix[i][right])
right -= 1 #左移
if left > right:
break
for i in range(right, left - 1, -1):
res.append(matrix[botton][i])
botton -= 1
if top > botton:
break
for i in range(botton, top - 1, -1):
res.append(matrix[i][left])
left += 1
if left > right:
break
return res