fn print_matrix_in_spiral_form(matrix: &[Vec<i32>]) {
if matrix.is_empty() || matrix[0].is_empty() {
return;
}
let (mut top, mut bottom) = (0, matrix.len() - 1);
let (mut left, mut right) = (0, matrix[0].len() - 1);
loop {
if left > right {
break;
}
// top row
for i in left..=right {
print!("{} ", matrix[top][i]);
}
println!();
top += 1; // next row
if top > bottom {
break;
}
// right column
for i in top..=bottom {
print!("{} ", matrix[i][right]);
}
println!();
right -= 1; // previous column
if left > right {
break;
}
// bottom row
for i in (left..=right).rev() {
print!("{} ", matrix[bottom][i]);
}
println!();
bottom -= 1; // previous row
if top > bottom {
break;
}
// left column
for i in (top..=bottom).rev() {
print!("{} ", matrix[i][left]);
}
println!();
left += 1; // next column
}
}
fn main() {
let matrix = vec![
vec![ 1, 2, 3, 4],
vec![ 5, 6, 7, 8],
vec![ 9, 10, 11, 12],
vec![13, 14, 15, 16],
];
print_matrix_in_spiral_form(&matrix);
}
/*
run:
1 2 3 4
8 12 16
15 14 13
9 5
6 7
11
10
*/