forked from tcandzq/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.py
More file actions
77 lines (66 loc) · 1.92 KB
/
SpiralMatrix.py
File metadata and controls
77 lines (66 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/11 21:47
# @Author : tc
# @File : SpiralMatrix.py
"""
题号 54 螺旋矩阵
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
参考:https://leetcode-cn.com/problems/spiral-matrix/solution/cxiang-xi-ti-jie-by-youlookdeliciousc-3/
"""
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
if not matrix:
return res
up = 0
down = len(matrix) - 1
left = 0
right = len(matrix[0]) - 1
while True:
for i in range(left,right+1): # 1.从左边移动到最右
res.append(matrix[up][i])
up += 1 # 2.重新设定上边界,若上边界大于下边界,则遍历遍历完成,下同
if up > down:
break
for i in range(up,down+1):
res.append(matrix[i][right]) # 3. 从上到下
right -= 1 # 重新设定右边界
if left > right:
break
for i in range(right,left-1,-1): # 从右往左
res.append(matrix[down][i])
down -= 1 # 重新设定下边界
if down < up:
break
for i in range(down,up-1,-1): # 从下往上
res.append(matrix[i][left])
left += 1 # 重新设定左边界
if left > right:
break
return res
if __name__ == '__main__':
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
solution = Solution()
print(solution.spiralOrder(matrix))