2025-07-10 14:13:01 +08:00
|
|
|
struct Solution;
|
|
|
|
impl Solution {
|
2025-09-04 11:31:56 +08:00
|
|
|
pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
|
|
|
|
let mut top_x = 0;
|
|
|
|
let mut left_y = 0;
|
|
|
|
let mut bottom_x = matrix.len() as i32 - 1;
|
|
|
|
let mut right_y = matrix[0].len() as i32 - 1;
|
|
|
|
let mut next_x = 0;
|
|
|
|
let mut next_y = 1;
|
|
|
|
let mut pos = (0, 0);
|
|
|
|
|
|
|
|
let mut res = vec![matrix[0][0]];
|
|
|
|
|
|
|
|
let mut next_pos = || {
|
|
|
|
let mut new_pos = (pos.0 + next_x, pos.1 + next_y);
|
|
|
|
if new_pos.0 > bottom_x || new_pos.0 < top_x || new_pos.1 > right_y || new_pos.1 < left_y {
|
|
|
|
(next_x, next_y) = match (next_x, next_y) {
|
|
|
|
(0, 1) => {
|
|
|
|
top_x += 1;
|
|
|
|
(1, 0)
|
2025-08-18 14:16:41 +08:00
|
|
|
}
|
2025-09-04 11:31:56 +08:00
|
|
|
(1, 0) => {
|
|
|
|
right_y -= 1;
|
|
|
|
(0, -1)
|
|
|
|
}
|
|
|
|
(0, -1) => {
|
|
|
|
bottom_x -= 1;
|
|
|
|
(-1, 0)
|
|
|
|
}
|
|
|
|
(-1, 0) => {
|
|
|
|
left_y += 1;
|
|
|
|
(0, 1)
|
|
|
|
}
|
|
|
|
_ => (0, 0),
|
2025-08-18 14:16:41 +08:00
|
|
|
};
|
|
|
|
|
2025-09-04 11:31:56 +08:00
|
|
|
new_pos = (pos.0 + next_x, pos.1 + next_y);
|
|
|
|
if new_pos.0 > bottom_x
|
|
|
|
|| new_pos.0 < top_x
|
|
|
|
|| new_pos.1 > right_y
|
|
|
|
|| new_pos.1 < left_y
|
|
|
|
{
|
|
|
|
return false;
|
2025-08-18 14:16:41 +08:00
|
|
|
}
|
|
|
|
}
|
2025-09-04 11:31:56 +08:00
|
|
|
pos = new_pos;
|
|
|
|
res.push(matrix[pos.0 as usize][pos.1 as usize]);
|
|
|
|
true
|
|
|
|
};
|
|
|
|
while next_pos() {}
|
|
|
|
res
|
2025-07-10 14:13:01 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2025-09-04 11:31:56 +08:00
|
|
|
let sl = Solution::spiral_order(vec![
|
|
|
|
vec![1, 2, 3, 4],
|
|
|
|
vec![5, 6, 7, 8],
|
|
|
|
vec![9, 10, 11, 12],
|
|
|
|
]);
|
2025-07-29 11:20:14 +08:00
|
|
|
println!("{:?}", sl);
|
2025-07-10 14:13:01 +08:00
|
|
|
}
|