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
61
62
63
64
65
66
67
68
| // @lc code=start
impl Solution {
/// ## 解题思路
pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
let mut res = vec![];
let (mut l, mut r, mut u, mut d) = (0, matrix[0].len() - 1, 0, matrix.len() - 1);
while l <= r && u <= d {
// 左->右
for col in l..=r {
res.push(matrix[u][col]);
}
if u < d {
u += 1; // u向下移一行
} else {
break;
}
// 上->下
for row in u..=d {
res.push(matrix[row][r]);
}
if r > l {
r -= 1; // r左移一列
} else {
break;
}
// 右->左
for col in (l..=r).rev() {
res.push(matrix[d][col]);
}
if d > u {
d -= 1; //
} else {
break;
}
// 下->上
for row in (u..=d).rev() {
res.push(matrix[row][l]);
}
if l < r {
l += 1; //
} else {
break;
}
}
res
}
}
// @lc code=end
struct Solution;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
assert_eq!(
Solution::spiral_order(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]),
vec![1, 2, 3, 6, 9, 8, 7, 4, 5]
);
assert_eq!(Solution::spiral_order(vec![vec![3], vec![2]]), vec![3, 2]);
}
}
|