
Problem
Solution
Submissions
Spiral Order Traversal of a Matrix
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to return all elements of a matrix in spiral order. Given an m x n matrix, return all elements of the matrix in spiral order, starting from the top-left corner and moving clockwise.
Example 1
- Input: matrix = [
[1,2,3],
[4,5,6],
[7,8,9]] - Output: [1,2,3,6,9,8,7,4,5]
- Explanation:
- Matrix:
1 2 3
4 5 6
7 8 9 - Spiral order: 1→2→3→6→9→8→7→4→5
- Matrix:
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]
- Explanation:
- Matrix:
1 2 3 4
5 6 7 8
9 10 11 12 - Spiral order: 1→2→3→4→8→12→11→10→9→5→6→7
- Matrix:
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 10
- -100 ≤ matrix[i][j] ≤ 100
- Time Complexity: O(m*n)
- Space Complexity: O(1) (excluding the output array)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Define four boundaries: top, right, bottom, and left
- Traverse the matrix in spiral order by processing one layer at a time
- Update the boundaries after processing each side of the current layer
- Be careful with the termination condition when the matrix is not square
- Add each visited element to the result list