用python打印螺旋矩阵元素的程序
假设我们有一个2D矩阵mat。我们必须以螺旋方式打印矩阵元素。首先从第一行(mat [0,0])开始打印整个内容,然后按最后列进行打印,然后是最后一行,依此类推,从而以螺旋方式打印元素。
因此,如果输入如下:
7 | 10 | 9 |
---|---|---|
2 | 9 | 1 |
6 | 2 | 3 |
9 | 1 | 4 |
2 | 7 | 5 |
9 | 9 | 11 |
那么输出将是[7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]
为解决此问题,我们将遵循以下步骤:
- d:=0
- 顶部:=0,下降:=矩阵的行数-1,左:=0,右:=矩阵的列数-1
- c:=0
- res:=全新的列表
- 方向:=0
- while top <= down and left <= right,do
- 如果direction与0相同,则
- for i in range left to right + 1,do
- insert matrix[top, i] into res
- top := top + 1
- 如果direction与1相同,则
- for i in range top to down + 1,do
- insert matrix[i, right] into res
- right := right – 1
- 如果direction与2相同,则
- for i in range right to left – 1,decrease by 1,do
- insert matrix[down, i] into res
- down := down – 1
- 如果direction与3相同,则
- for i in range down to top – 1,decrease by 1,do
- insert matrix[i, left] into res
- left := left+ 1
- 如果direction与0相同,则
- direction:=(direction + 1)mod 4
- 返回res
让我们看以下实现以获得更好的理解:
示例
class Solution:
def solve(self, matrix):
d = 0
top = 0
down = len(matrix) - 1
left = 0
right = len(matrix[0]) - 1
c = 0
res = []
direction = 0
while top <= down and left <= right:
if direction == 0:
for i in range(left, right + 1):
res.append(matrix[top][i])
top += 1
if direction == 1:
for i in range(top, down + 1):
res.append(matrix[i][right])
right -= 1
if direction == 2:
for i in range(right, left - 1, -1):
res.append(matrix[down][i])
down -= 1
if direction == 3:
for i in range(down, top - 1, -1):
res.append(matrix[i][left])
left += 1
direction = (direction + 1) % 4
return res
ob = Solution()
matrix = [
[7, 10, 9],
[2, 9, 1],
[6, 2, 3],
[9, 1, 4],
[2, 7, 5],
[9, 9, 11]
]
print(ob.solve(matrix))
输入
[
[7, 10, 9],
[2, 9, 1],
[6, 2, 3],
[9, 1, 4],
[2, 7, 5],
[9, 9, 11]
]
输出
[7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]