leet_rs/
spiral_matrix.rs

1pub struct SpiralMatrixSolution {}
2
3impl SpiralMatrixSolution {
4    /// Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
5    ///
6    /// # Arguments
7    /// * `matrix` - A vector of vectors representing a matrix of integers.
8    ///
9    /// # Returns
10    /// (`Vec<i32>`) A vector of integers representing the elements of the matrix in spiral order.
11    ///
12    /// # Examples
13    ///
14    /// ```
15    /// use leet_rs::spiral_matrix::SpiralMatrixSolution;
16    ///
17    /// let matrix = vec![
18    ///     vec![1, 2, 3],
19    ///     vec![4, 5, 6],
20    ///     vec![7, 8, 9]
21    /// ];
22    /// let result = SpiralMatrixSolution::spiral_order(matrix);
23    /// assert_eq!(result, vec![1, 2, 3, 6, 9, 8, 7, 4, 5]);
24    /// ```
25    ///
26    /// # Time complexity
27    /// O(m x n) where m is the number of rows and n is the number of columns in the matrix.
28    ///
29    /// # Space complexity
30    /// O(m x n) where m is the number of rows and n is the number of columns in the matrix.
31    pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
32        if matrix.is_empty() {
33            return vec![];
34        }
35
36        let mut result = Vec::new();
37        let mut top = 0;
38        let mut bottom = matrix.len() - 1;
39        let mut left = 0;
40        let mut right = matrix[0].len() - 1;
41
42        // Handle single row
43        if bottom == 0 {
44            return matrix[0].clone();
45        }
46
47        // Handle single column
48        if right == 0 {
49            for i in 0..=bottom {
50                result.push(matrix[i][0]);
51            }
52            return result;
53        }
54
55        while top <= bottom && left <= right {
56            // Traverse Right
57            for i in left..=right {
58                result.push(matrix[top][i]);
59            }
60            top += 1;
61
62            // Traverse Down
63            for i in top..=bottom {
64                result.push(matrix[i][right]);
65            }
66            right -= 1;
67
68            // Traverse Left
69            if top <= bottom {
70                for i in (left..=right).rev() {
71                    result.push(matrix[bottom][i]);
72                }
73                bottom -= 1;
74            }
75
76            // Traverse Up
77            if left <= right {
78                for i in (top..=bottom).rev() {
79                    result.push(matrix[i][left]);
80                }
81                left += 1;
82            }
83        }
84        result
85    }
86}