Skip to content

Commit 5bb82d8

Browse files
committed
q59
1 parent adb5ecf commit 5bb82d8

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed

src/array/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
mod q35;
22
mod q27;
33
mod q209;
4+
mod q59;

src/array/q59.rs

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
//! 给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
2+
//!
3+
//! 示例:
4+
//!
5+
//! 输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
6+
7+
8+
enum Direction {
9+
Up,
10+
Down,
11+
Left,
12+
Right,
13+
}
14+
15+
struct Solution ();
16+
impl Solution {
17+
pub fn rotate_matrix(n: u8) -> Vec<Vec<u8>> {
18+
let mut dir = Direction::Right;
19+
let mut x = 0;
20+
let mut y = 0;
21+
let mut level = 0;
22+
23+
let mut result = vec![vec![1; n as usize]; n as usize];
24+
for i in 1..n*n+1 {
25+
match dir {
26+
Direction::Up => {
27+
println!("UP: {:?} {:?}", y, x);
28+
result[y][x] = i;
29+
if y == level + 1 {
30+
dir = Direction::Right;
31+
level += 1;
32+
x += 1;
33+
} else {
34+
y -= 1;
35+
}
36+
},
37+
Direction::Down => {
38+
println!("Down: {:?} {:?}", y, x);
39+
result[y][x] = i;
40+
if y == (n as usize -1 -level) {
41+
dir = Direction::Left;
42+
x -= 1;
43+
} else {
44+
y += 1;
45+
}
46+
},
47+
Direction::Left => {
48+
println!("Left: {:?} {:?}", y, x);
49+
result[y][x] = i;
50+
if x == level as usize {
51+
dir = Direction::Up;
52+
y -= 1;
53+
} else {
54+
x -= 1;
55+
}
56+
57+
},
58+
Direction::Right => {
59+
println!("Right: {:?} {:?}", y, x);
60+
result[y][x] = i;
61+
if x == (n as usize - 1 - level) as usize {
62+
dir = Direction::Down;
63+
y += 1;
64+
} else {
65+
x += 1;
66+
}
67+
},
68+
}
69+
70+
}
71+
72+
73+
result
74+
75+
}
76+
}
77+
78+
79+
80+
#[cfg(test)]
81+
mod tests {
82+
use super::*;
83+
84+
#[test] fn common_test() {
85+
let v = Solution::rotate_matrix(5);
86+
87+
for vv in v.iter() {
88+
for i in vv.iter() {
89+
print!("{:?} ", i)
90+
}
91+
println!(" ")
92+
}
93+
94+
println!("{:?}", v);
95+
96+
97+
}
98+
}

0 commit comments

Comments
 (0)