CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
Spiral Matrix Traversal
matrix
simulation
# Spiral Matrix Traversal ## Difficulty Medium ## Tags `matrix`, `simulation` ## Problem Statement Given an `m x n` matrix, return all elements of the matrix in spiral order (starting from the top-left corner, going right, then down, then left, then up, and repeating). ## Constraints - m == matrix.length - n == matrix[i].length - 1 ≤ m, n ≤ 10 - -100 ≤ matrix[i][j] ≤ 100 ## Signatures ### Python ```python def spiral_order(matrix: List[List[int]]) -> List[int]: pass ``` ### Java ```java public class Solution { public List<Integer> spiral_order(List<List<Integer>> matrix) { return null; } } ``` ### Csharp ```csharp public class Solution { public IList<int> spiral_order(IList<IList<int>> matrix) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: vector<int> spiral_order(vector<vector<int>> matrix) { } }; ``` ### C ```c int* spiral_order(vector<int*> matrix) { } ``` ### Ruby ```ruby def spiral_order(matrix) end ``` ### Perl ```perl sub spiral_order { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def spiral_order(matrix: List[List[Int]]): List[Int] = { } } ``` ### Haskell ```haskell spiral_order :: ... -> ... spiral_order args = undefined ``` ### Clojure ```clojure (defn spiral_order [matrix] ) ``` ### Scheme ```scheme (define (spiral_order matrix) ) ``` ## Examples ### Example 1 **Input:** ``` matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] ``` **Output:** ``` [1, 2, 3, 6, 9, 8, 7, 4, 5] ``` **Explanation:** Start at 1, go right (1,2,3), down (6,9), left (8,7), up (4), right (5). ### Example 2 **Input:** ``` matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] ``` **Output:** ``` [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] ``` ### Example 3 **Input:** ``` matrix = [[1]] ``` **Output:** ``` [1] ``` ## Hints 1. Use four boundary variables: `top`, `bottom`, `left`, `right`. 2. Traverse in order: right along top row, down right column, left along bottom row, up left column. 3. Shrink boundaries after each direction. 4. Check bounds before each traversal to handle non-square matrices.
Login required
Please log in to view the solution editor and submit code.
Login
Register