#59
Medium Algorithms Spiral matrix ii
Array Matrix Simulation
74.7% acceptance
Jan 12, 2026
6887
287
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn generate_matrix(n: i32) -> Vec<Vec<i32>> {
let n = n as usize;
let mut matrix = vec![vec![0; n]; n];
let mut num = 1;
let mut top = 0;
let mut bottom = n - 1;
let mut left = 0;
let mut right = n - 1;
while top <= bottom && left <= right {
// Traverse right
for col in left..=right {
matrix[top][col] = num;
num += 1;
}
top += 1;
if top > bottom {
break;
}
// Traverse down
for row in top..=bottom {
matrix[row][right] = num;
num += 1;
}
if right == 0 {
break;
}
right -= 1;
if left > right {
break;
}
// Traverse left
for col in (left..=right).rev() {
matrix[bottom][col] = num;
num += 1;
}
if bottom == 0 {
break;
}
bottom -= 1;
if top > bottom {
break;
}
// Traverse up
for row in (top..=bottom).rev() {
matrix[row][left] = num;
num += 1;
}
left += 1;
}
matrix
}
}