Category | Difficulty | Likes | Dislikes |
---|
algorithms | Medium (76.50%) | 696 | - |
Tags
array
Companies
Unknown
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
1
2
| 输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
|
示例 2:
提示:
Discussion | Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
| struct Solution;
// @lc code=start
impl Solution {
/// ## 解题思路
pub fn generate_matrix(n: i32) -> Vec<Vec<i32>> {
let n = n as usize;
let (mut left, mut right, mut top, mut bottom) = (0, n - 1, 0, n - 1);
let mut res = vec![vec![0; n]; n];
let mut v = 1;
while left <= right && top <= bottom {
// 左->右
for col in left..=right {
res[top][col] = v;
v += 1;
}
if top < bottom {
top += 1;
} else {
break;
}
// 上->下
for row in top..=bottom {
res[row][right] = v;
v += 1;
}
if right > left {
right -= 1;
} else {
break;
}
// 右->左
for col in (left..=right).rev() {
res[bottom][col] = v;
v += 1;
}
if bottom > top {
bottom -= 1;
} else {
break;
}
// 下->上
for row in (top..=bottom).rev() {
res[row][left] = v;
v += 1;
}
if left < right {
left += 1;
} else {
break;
}
}
res
}
}
// @lc code=end
|