|
发表于 2022-1-26 23:05:52
|
显示全部楼层
- #把矩阵想像成一个正方形,那它有什么特征?对的它有四个面所以我们要定义它的4个面
- matrix = [[1,2,3,4],
- [5,6,7,8],
- [9,10,11,12],
- [13,14,15,16]]
- #防止矩阵发生改变,进行数据关联
- #获取列表的行的长度并赋值给 rows
- #过去列表的列的长度并赋值给 tall
- tows = len(matrix)
- #tows 与 tall 变量的作用:防止矩阵改变,代码无法判断运行,例如 矩阵为3*3,那么在下面代码中每一行都要 减少一个单位(-1)
- tall = len(matrix[0])
- left = 0 #左边
- right = tall - 1 #行长
- top = 0 #顶部
- bottom = tows - 1 #底部
- JIAYOU = [] #用来存储变量
- while left <= right and top <= bottom: #左边小于右边,顶部小于底部
- #若是我们用到range() ,它是取不到尾数的,所以我们要 + 1 ,超过范围才能取的到
- #从左往右遍历
- for col in range(left , right+1):
- JIAYOU.append(matrix[top][col])
- #从上到下遍历
- for row in range(top+1 , bottom + 1):
- JIAYOU.append(matrix[row][right])
- if left < right and top < bottom:
- #从右往左遍历
- for col in range(right-1 , left,-1):
- JIAYOU.append(matrix[bottom][col])
- #从下到上遍历
- for row in range(bottom , top , -1):
- JIAYOU.append(matrix[row][left])
-
- #当转外圈的时候部分固定的值都+1,要回到内圈的时候部分固定值都-1,这样就OK
- #判断条件是否满足
- left += 1
- right -= 1
-
- top += 1
- bottom -= 1
- print(JIAYOU)
复制代码 |
|