-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path59-Spiral_Matrix_II.rs
More file actions
48 lines (40 loc) · 1.24 KB
/
Copy path59-Spiral_Matrix_II.rs
File metadata and controls
48 lines (40 loc) · 1.24 KB
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
impl Solution {
pub fn generate_matrix(n: i32) -> Vec<Vec<i32>> {
let n = n as usize;
let mut matrix = vec![vec![0; n]; n];
let (mut top, mut bottom) = (0, n as i32 - 1);
let (mut left, mut right) = (0, n as i32 - 1);
let mut num = 1;
// Left → Right
// Top → Bottom
// Right → Left
// Bottom → Top
while top <= bottom && left <= right {
for col in left..=right {
matrix[top as usize][col as usize] = num;
num += 1;
}
top += 1;
for row in top..=bottom {
matrix[row as usize][right as usize] = num;
num += 1;
}
right -= 1;
if top <= bottom {
for col in (left..=right).rev() {
matrix[bottom as usize][col as usize] = num;
num += 1;
}
bottom -= 1;
}
if left <= right {
for row in (top..=bottom).rev() {
matrix[row as usize][left as usize] = num;
num += 1;
}
left += 1;
}
}
matrix
}
}