文章目录
- 54.螺旋矩阵
- 59.螺旋矩阵II
54.螺旋矩阵
59.螺旋矩阵 II
54.螺旋矩阵
总体的思路分析:
顺时针,先遍历右边,再下面,再往左,再向上,然后再缩小一圈范围即可
原本的代码情况
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix)
n = len(matrix[0])
ans = []
left ,top = 0,0
right,bottom = n-1,m-1
while top <= bottom and left<= right:
for i in range(left,right+1):
ans.append(matrix[top][i])
for i in range(top+1,bottom+1):
ans.append(matrix[i][right])
for i in range(right-1,left-1,-1):
ans.append(matrix[bottom][i])
for i in range(bottom-1,top,-1):
ans.append(matrix[i][left])
left,top = left+1,top+1
right,bottom = right-1,bottom-1
return ans
就是发现当面对长方形的时候会出现重复的元素
分析问题的错因?
再看另一个正确的代码
两个代码的区别就是对于边界值的处理,处理完边界值之后需要对边界值进行判断
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix)
n = len(matrix[0])
ans = []
left ,top = 0,0
right,bottom = n-1,m-1
while top <= bottom 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):
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 bottom<top:
break
for i in range(bottom,top-1,-1):
ans.append(matrix[i][left])
left +=1
if left>right:
break
return ans
59.螺旋矩阵II
这个是正方形,相对来说简单一点
我们可以考虑在完成一圈之后再对边界值修改
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
left = 0
right = n-1
top = 0
bottom = n-1
matrix = [[0] * n for _ in range (n)]
count = 1
while top<=bottom and left<=right:
for i in range(left,right+1):
matrix[top][i] = count
count+=1
for i in range(top+1,bottom+1):
matrix[i][right] = count
count+=1
for i in range (right-1,left-1,-1):
matrix[bottom][i] = count
count +=1
for i in range (bottom-1,top,-1):
matrix[i][left] = count
count +=1
top+=1
right-=1
bottom-=1
left+=1
return matrix
为了应对长方形的情况,需要在每次修改边界之后对边界判断
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
left = 0
right = n-1
top = 0
bottom = n-1
matrix = [[0] * n for _ in range (n)]
count = 1
while top<=bottom and left<=right:
for i in range(left,right+1):
matrix[top][i] = count
count+=1
top+=1
if top > bottom:
break
for i in range(top,bottom+1):
matrix[i][right] = count
count+=1
right-=1
if right<left:
break
for i in range (right,left-1,-1):
matrix[bottom][i] = count
count +=1
bottom-=1
if bottom<top:
break
for i in range (bottom,top-1,-1):
matrix[i][left] = count
count +=1
left+=1
if left>right:
break
return matrix