|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Ari小虎鱼 于 2022-4-18 18:25 编辑
- matrix = [[1,2,3,4],
- [5,6,7,8],
- [9,10,11,12]]
- #初始化
- top = 0
- bottom = len(matrix)
- right = len(matrix[0])
- left = 0
- spiral = []
- #遍历一周
- while True:
- for each in range(left,right):
- spiral.append(matrix[top][each])
- for each in range((top+1),bottom):
- spiral.append(matrix[each][right-1])
- for each in range(right-2,left-1,-1):
- spiral.append(matrix[bottom-1][each])
- for each in range(bottom-2,top,-1):
- spiral.append(matrix[each][left])
- left += 1
- right -=1
- top += 1
- bottom -= 1
- if left > right or top > bottom:
- break
-
- #打印
- print(spiral)
复制代码
代码运行整体没问题,就是结尾会再返回
- [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6]
- >>>
复制代码
请大佬看看这个应该怎么改?
你可以把第三个和第四个for循环的逻辑改一改
第三个不用到最左边的元素,也就是下标为0的元素
第四个循环就可以从最左边的元素往上走
|
|