Skip to content

Commit 98d0619

Browse files
committed
螺旋矩阵2
螺旋矩阵2
1 parent 6a9b2f0 commit 98d0619

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

leetcode_array/main.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
* [长度最小的子数组(滑动窗口)](长度最小的子数组.md)
1313
* [螺旋矩阵II](螺旋矩阵2.md)
1414

15-
15+
<!--
1616
1. [两数之和](两数之和.md)
1717
2. [删除排序数组中的重复项](删除排序数组中的重复项.md)
1818
3. [移除元素](移除元素.md)
@@ -55,3 +55,4 @@
5555
40. [矩阵中的幻方](矩阵中的幻方.md)
5656
41. [转置矩阵](转置矩阵.md)
5757
42. [单调数列](单调数列.md)
58+
-->

leetcode_array/螺旋矩阵2.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,38 @@
11
# 59.螺旋矩阵II
22
给你一个正整数n,生成一个包含1到n2所有元素,且元素按顺时针顺序螺旋排列的nxn正方形矩阵matrix。
33
![](../pic/leetcode_array/59_1.png)
4+
5+
## 模拟顺时针顺序填充矩阵
6+
**模拟四个方向**
7+
* 从左向右:行索引不变,列索引增大
8+
* 从上向下:行索引增大,列索引不变
9+
* 从右向左:行索引不变,列索引减小
10+
* 从下向上:行索引减小,列索引不变
11+
* 初始化元素全部为0,当索引越界,或者碰到不为0的值,就应该改变方向
12+
13+
```python
14+
def generateMatrix(n):
15+
# 定义四个移动方向
16+
# (0, 1): 从左向右, row+0, col+1
17+
# (1, 0): 从上向下 row+1, col+0
18+
# (0, -1): 从右向左 row+0, col-1
19+
# (-1, 0): 从下向上 row-1, col+0
20+
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
21+
# 初始化
22+
matrix = [[0] * n for _ in range(n)]
23+
row, col, dirs_index = 0, 0, 0
24+
for i in range(1, n*n+1):
25+
matrix[row][col] = i
26+
# 计算下一个填充位置
27+
dx, dy = dirs[dirs_index]
28+
r = row + dx
29+
c = col + dy
30+
if r >= n or r < 0 or c >= n or c < 0 or matrix[r][c] > 0:
31+
# 改变方向
32+
dirs_index = (dirs_index + 1) % 4
33+
dx, dy = dirs[dirs_index]
34+
row = row + dx
35+
col = col + dy
36+
37+
return matrix
38+
```

0 commit comments

Comments
 (0)