#54
Medium Algorithms Spiral matrix
Array Matrix Simulation
56.2% acceptance
Jan 12, 2026
17301
1558
Given an m x n matrix, return all elements of the matrix in spiral order.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
let mut result = Vec::new();
if matrix.is_empty() {
return result;
}
let m = matrix.len();
let n = matrix[0].len();
let mut top = 0;
let mut bottom = m - 1;
let mut left = 0;
let mut right = n - 1;
while top <= bottom && left <= right {
// Traverse right
for col in left..=right {
result.push(matrix[top][col]);
}
top += 1;
if top > bottom {
break;
}
// Traverse down
for row in top..=bottom {
result.push(matrix[row][right]);
}
if right == 0 {
break;
}
right -= 1;
if left > right {
break;
}
// Traverse left
for col in (left..=right).rev() {
result.push(matrix[bottom][col]);
}
if bottom == 0 {
break;
}
bottom -= 1;
if top > bottom {
break;
}
// Traverse up
for row in (top..=bottom).rev() {
result.push(matrix[row][left]);
}
left += 1;
}
result
}
}