impl Solution {
pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
// Initialize the result vector to store the spiral order.
let mut res = vec![];
// Initialize pointers for the current boundaries of the matrix slice we are working on.
// `l` and `r` for left and right columns, `t` and `b` for top and bottom rows.
let mut l = 0; // Left boundary
let mut r = matrix[0].len(); // Right boundary (exclusive)
let mut t = 0; // Top boundary
let mut b = matrix.len(); // Bottom boundary (exclusive)
// Continue looping until the left boundary is less than the right, and the top boundary is less than the bottom.
// This condition ensures that we are always working within the valid range of the matrix.
while l < r && t < b {
// Traverse from left to right on the top row.
for i in l..r {
res.push(matrix[t][i]);
}
t += 1; // Move the top boundary down as this row is now done.
// Traverse from top to bottom on the rightmost column.
for i in t..b {
res.push(matrix[i][r - 1]);
}
r -= 1; // Move the right boundary left as this column is now done.
// Check if we have covered all rows and columns to prevent double counting the elements in the final row or column.
if !(l < r && t < b) {
break;
}
// Traverse from right to left on the bottom row.
for i in (l..r).rev() {
res.push(matrix[b - 1][i]);
}
b -= 1; // Move the bottom boundary up as this row is now done.
// Traverse from bottom to top on the leftmost column.
for i in (t..b).rev() {
res.push(matrix[i][l]);
}
l += 1; // Move the left boundary right as this column is now done.
}
// Return the result vector containing the elements of the matrix in spiral order.
res
}
}