Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7f33567

Browse files
Merge pull request youngyangyang04#2413 from maolupku/master
加入新解法:螺旋矩阵定义4个边界
2 parents 88bb277 + 0e34b46 commit 7f33567

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

‎problems/0054.螺旋矩阵.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,47 @@ class Solution(object):
306306
return result
307307
```
308308

309+
版本二:定义四个边界
310+
```python
311+
class Solution(object):
312+
def spiralOrder(self, matrix):
313+
"""
314+
:type matrix: List[List[int]]
315+
:rtype: List[int]
316+
"""
317+
if not matrix:
318+
return []
319+
320+
rows = len(matrix)
321+
cols = len(matrix[0])
322+
top, bottom, left, right = 0, rows - 1, 0, cols - 1
323+
print_list = []
324+
325+
while top <= bottom and left <= right:
326+
# 从左到右
327+
for i in range(left, right + 1):
328+
print_list.append(matrix[top][i])
329+
top += 1
330+
331+
# 从上到下
332+
for i in range(top, bottom + 1):
333+
print_list.append(matrix[i][right])
334+
right -= 1
335+
336+
# 从右到左
337+
if top <= bottom:
338+
for i in range(right, left - 1, -1):
339+
print_list.append(matrix[bottom][i])
340+
bottom -= 1
341+
342+
# 从下到上
343+
if left <= right:
344+
for i in range(bottom, top - 1, -1):
345+
print_list.append(matrix[i][left])
346+
left += 1
347+
348+
return print_list
349+
```
309350

310351

311352
<p align="center">

‎problems/0059.螺旋矩阵II.md‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,50 @@ class Solution:
207207
return nums
208208
```
209209

210+
版本二:定义四个边界
211+
```python
212+
class Solution(object):
213+
def generateMatrix(self, n):
214+
if n <= 0:
215+
return []
216+
217+
# 初始化 n x n 矩阵
218+
matrix = [[0]*n for _ in range(n)]
219+
220+
# 初始化边界和起始值
221+
top, bottom, left, right = 0, n-1, 0, n-1
222+
num = 1
223+
224+
while top <= bottom and left <= right:
225+
# 从左到右填充上边界
226+
for i in range(left, right + 1):
227+
matrix[top][i] = num
228+
num += 1
229+
top += 1
230+
231+
# 从上到下填充右边界
232+
for i in range(top, bottom + 1):
233+
matrix[i][right] = num
234+
num += 1
235+
right -= 1
236+
237+
# 从右到左填充下边界
238+
239+
for i in range(right, left - 1, -1):
240+
matrix[bottom][i] = num
241+
num += 1
242+
bottom -= 1
243+
244+
# 从下到上填充左边界
245+
246+
for i in range(bottom, top - 1, -1):
247+
matrix[i][left] = num
248+
num += 1
249+
left += 1
250+
251+
return matrix
252+
```
253+
210254
### JavaScript:
211255

212256
```javascript

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /