From da4f5de90905e87e6804ca6c172750c9fc5e4370 Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Wed, 19 Jan 2022 22:32:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00054.=E8=9E=BA=E6=97=8B?= =?UTF-8?q?=E7=9F=A9=E9=98=B5=20python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0054.螺旋矩阵.md | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/0054.螺旋矩阵.md b/problems/0054.螺旋矩阵.md index 3f85c607..ccf6f471 100644 --- a/problems/0054.螺旋矩阵.md +++ b/problems/0054.螺旋矩阵.md @@ -131,7 +131,46 @@ public: * [59.螺旋矩阵II](https://leetcode-cn.com/problems/spiral-matrix-ii/) * [剑指Offer 29.顺时针打印矩阵](https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/) +## 其他语言版本 +Python: +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + left, right, up, down = 0, n - 1, 0, m - 1 # 定位四个方向的边界,闭区间 + res = [] + + while True: + for i in range(left, right + 1): # 上边,从左到右 + res.append(matrix[up][i]) + up += 1 # 上边界下移 + if len(res) >= m * n: # 判断是否已经遍历完 + break + + for i in range(up, down + 1): # 右边,从上到下 + res.append(matrix[i][right]) + right -= 1 # 右边界左移 + + if len(res) >= m * n: + break + + for i in range(right, left - 1, -1): # 下边,从右到左 + res.append(matrix[down][i]) + down -= 1 # 下边界上移 + + if len(res) >= m * n: + break + + for i in range(down, up - 1, -1): # 左边,从下到上 + res.append(matrix[i][left]) + left += 1 # 左边界右移 + + if len(res) >= m * n: + break + + return res +``` -----------------------