|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 成成是我 于 2022-12-12 08:36 编辑
请按照顺时针螺旋顺序输出矩阵中的所有元素
- >>> matrix = [[1, 2, 3, 4],
- ... [5, 6, 7, 8],
- ... [9, 10, 11, 12]]
- 那么将输出:
- [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
- 代码清单:
- matrix = [[1, 2, 3, 4],
- [5, 6, 7, 8],
- [9, 10, 11, 12]]
-
- rows = len(matrix)
- cols = len(matrix[0])
-
- left = 0
- right = cols - 1
- top = 0
- bottom = rows - 1
-
- result = []
-
- while left <= right and top <= bottom:
- # 从左往右遍历
- for col in range(left, right + 1):
- result.append(matrix[top][col])
-
- # 从上往下遍历
- for row in range(top + 1, bottom + 1):
- result.append(matrix[row][right])
-
- if left < right and top < bottom:
- # 从右往左遍历
- for col in range(right - 1, left, -1):
- result.append(matrix[bottom][col])
-
- # 从下往上遍历
- for row in range(bottom, top, -1):
- result.append(matrix[row][left])
-
- left = left + 1
- right = right - 1
- top = top + 1
- bottom = bottom - 1
-
- print(result)
复制代码
请大佬解释下红字部分:
1.right 和botton 初始值为什么要-1?
2.请解释下循环范围
感谢感谢!
- # 从左往右遍历,首先是第一行既top=0保持不变,matrix[top]=[1, 2, 3, 4],col从0到right值就可以把matrix[top]的所有值取出来,既1, 2, 3, 4
- for col in range(left, right + 1):
- result.append(matrix[top][col]) #行是确定的,即为top
- # 从上往下遍历,这个时候从最右侧这列开始(最右侧这一列的第二个元素开始,因为这一列第一个元素既4已经在上面被取出来了),这一列的元素来着不同的matrix[row]的最后一个元素。既 8, 12
- for row in range(top + 1, bottom + 1):
- result.append(matrix[row][right]) #列是确定的,即为right
- if left < right and top < bottom:
- # 从右往左遍历,这个时候从最下面一行开始(最下面一行的倒数第二个元素开始,因为这一行的最后第一个元素既12已经在上面被取出来了),既11, 10, 9。
- for col in range(right - 1, left, -1):
- result.append(matrix[bottom][col]) #行是确定的,即为botton
- # 从下往上遍历
- for row in range(bottom, top, -1):
- result.append(matrix[row][left]) #列是确定的,即为left
复制代码
|
|