|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 wangyanren 于 2022-8-20 19:42 编辑
请按照顺时针螺旋顺序输出矩阵中的所有元素,输出结果:[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
atrix = [[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)
我的思路是这样:
往右往下往左往上走一圈为一个rounds
用for循环设置rounds参数限制位置
用while循环分别走四个方向并打印(也可以将元素输出到列表啊啥的)
matrix = [[1,2,3,4,5],
[6,7,8,9,0],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25],
[26,27,28,29,30]]
# 获取列表长度6
rows = len(matrix)
# 获取列表宽度5
cols = len(matrix[0])
for rounds in range(3):
# 将位置参数初始化为第rounds圈,第一位置为[rounds][rounds]
left = top = rounds
# 右边界限为列表宽度-圈数-1
right = cols - rounds - 1
# 底部界限为列表长度-圈数-1
bottom = rows - rounds - 1
# 判定是否还有继续循环的必要,left>=right且top>=bottom则跳出
if left >= right and top >= bottom:
break
# 顶部为第一序列
while left <= right:
# 输出第top行第left列
print(matrix[top][left])
# 位置往右移动
left += 1
# 右边为第二序列
while top < bottom:
# 位置往下移动
top += 1
# 输出top行right列
print(matrix[top][right])
while right > rounds:
# 位置往左移动
right -= 1
# 输出bottom行right列
print(matrix[bottom][right])
while bottom > rounds+1:
# 位置往上移动
bottom-=1
# 输出bottom行rounds列
print(matrix[bottom][rounds])
|
评分
-
查看全部评分
|