mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
@ -306,6 +306,47 @@ class Solution(object):
|
|||||||
return result
|
return result
|
||||||
```
|
```
|
||||||
|
|
||||||
|
版本二:定义四个边界
|
||||||
|
```python
|
||||||
|
class Solution(object):
|
||||||
|
def spiralOrder(self, matrix):
|
||||||
|
"""
|
||||||
|
:type matrix: List[List[int]]
|
||||||
|
:rtype: List[int]
|
||||||
|
"""
|
||||||
|
if not matrix:
|
||||||
|
return []
|
||||||
|
|
||||||
|
rows = len(matrix)
|
||||||
|
cols = len(matrix[0])
|
||||||
|
top, bottom, left, right = 0, rows - 1, 0, cols - 1
|
||||||
|
print_list = []
|
||||||
|
|
||||||
|
while top <= bottom and left <= right:
|
||||||
|
# 从左到右
|
||||||
|
for i in range(left, right + 1):
|
||||||
|
print_list.append(matrix[top][i])
|
||||||
|
top += 1
|
||||||
|
|
||||||
|
# 从上到下
|
||||||
|
for i in range(top, bottom + 1):
|
||||||
|
print_list.append(matrix[i][right])
|
||||||
|
right -= 1
|
||||||
|
|
||||||
|
# 从右到左
|
||||||
|
if top <= bottom:
|
||||||
|
for i in range(right, left - 1, -1):
|
||||||
|
print_list.append(matrix[bottom][i])
|
||||||
|
bottom -= 1
|
||||||
|
|
||||||
|
# 从下到上
|
||||||
|
if left <= right:
|
||||||
|
for i in range(bottom, top - 1, -1):
|
||||||
|
print_list.append(matrix[i][left])
|
||||||
|
left += 1
|
||||||
|
|
||||||
|
return print_list
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
|
@ -207,6 +207,50 @@ class Solution:
|
|||||||
return nums
|
return nums
|
||||||
```
|
```
|
||||||
|
|
||||||
|
版本二:定义四个边界
|
||||||
|
```python
|
||||||
|
class Solution(object):
|
||||||
|
def generateMatrix(self, n):
|
||||||
|
if n <= 0:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 初始化 n x n 矩阵
|
||||||
|
matrix = [[0]*n for _ in range(n)]
|
||||||
|
|
||||||
|
# 初始化边界和起始值
|
||||||
|
top, bottom, left, right = 0, n-1, 0, n-1
|
||||||
|
num = 1
|
||||||
|
|
||||||
|
while top <= bottom and left <= right:
|
||||||
|
# 从左到右填充上边界
|
||||||
|
for i in range(left, right + 1):
|
||||||
|
matrix[top][i] = num
|
||||||
|
num += 1
|
||||||
|
top += 1
|
||||||
|
|
||||||
|
# 从上到下填充右边界
|
||||||
|
for i in range(top, bottom + 1):
|
||||||
|
matrix[i][right] = num
|
||||||
|
num += 1
|
||||||
|
right -= 1
|
||||||
|
|
||||||
|
# 从右到左填充下边界
|
||||||
|
|
||||||
|
for i in range(right, left - 1, -1):
|
||||||
|
matrix[bottom][i] = num
|
||||||
|
num += 1
|
||||||
|
bottom -= 1
|
||||||
|
|
||||||
|
# 从下到上填充左边界
|
||||||
|
|
||||||
|
for i in range(bottom, top - 1, -1):
|
||||||
|
matrix[i][left] = num
|
||||||
|
num += 1
|
||||||
|
left += 1
|
||||||
|
|
||||||
|
return matrix
|
||||||
|
```
|
||||||
|
|
||||||
### JavaScript:
|
### JavaScript:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
Reference in New Issue
Block a user