|
20鱼币
- 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)
复制代码
我试过了,这里去掉第 24 行的代码也能正常运行
所以说,第 24 行代码究竟有什么作用?!!!
哪位大佬可以解释一下的?
解释出来的人,重金悬赏20鱼币!!!
- matrix = [[1],
- [5],
- [9]]
- 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): # 这个跑完结果为 [1, 5, 9]
- result.append(matrix[row][right])
- # 从右往左遍历
- for col in range(right - 1, left, -1): # 不跑
- result.append(matrix[bottom][col])
- # 从下往上遍历
- for row in range(bottom, top, -1): # 这个会多跑一遍 1, 5, 9, 9, 5
- result.append(matrix[row][left])
- left = left + 1
- right = right - 1
- top = top + 1
- bottom = bottom - 1
- print(result)
复制代码
|
|