Skip to content

Commit 97bc7ef

Browse files
Merge pull request youngyangyang04#1039 from leeeeeeewii/54
添加0054.螺旋矩阵 python版本
2 parents de193e2 + da4f5de commit 97bc7ef

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

problems/0054.螺旋矩阵.md

+40-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,46 @@ public:
131131
* [59.螺旋矩阵II](https://leetcode-cn.com/problems/spiral-matrix-ii/)
132132
* [剑指Offer 29.顺时针打印矩阵](https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/)
133133

134-
134+
## 其他语言版本
135+
Python:
136+
```python
137+
class Solution:
138+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
139+
m, n = len(matrix), len(matrix[0])
140+
left, right, up, down = 0, n - 1, 0, m - 1 # 定位四个方向的边界,闭区间
141+
res = []
142+
143+
while True:
144+
for i in range(left, right + 1): # 上边,从左到右
145+
res.append(matrix[up][i])
146+
up += 1 # 上边界下移
147+
148+
if len(res) >= m * n: # 判断是否已经遍历完
149+
break
150+
151+
for i in range(up, down + 1): # 右边,从上到下
152+
res.append(matrix[i][right])
153+
right -= 1 # 右边界左移
154+
155+
if len(res) >= m * n:
156+
break
157+
158+
for i in range(right, left - 1, -1): # 下边,从右到左
159+
res.append(matrix[down][i])
160+
down -= 1 # 下边界上移
161+
162+
if len(res) >= m * n:
163+
break
164+
165+
for i in range(down, up - 1, -1): # 左边,从下到上
166+
res.append(matrix[i][left])
167+
left += 1 # 左边界右移
168+
169+
if len(res) >= m * n:
170+
break
171+
172+
return res
173+
```
135174

136175
-----------------------
137176
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)