
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Spiral Matrix
								Certification: Intermediate Level
								Accuracy: 0%
								Submissions: 0
								Points: 10
							
							Write a C program that, given an M x N matrix, returns all elements of the matrix in spiral order. The spiral starts at the top-left corner of the matrix and proceeds in a clockwise direction, gradually moving inward until all elements have been visited.
Example 1
- Input: matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
 - Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
 - Explanation: 
    
- Step 1: Start at the top-left corner (1).
 - Step 2: Move right until the end of the first row (1 -> 2 -> 3).
 - Step 3: Move down until the end of the last column (3 -> 6 -> 9).
 - Step 4: Move left until the start of the last row (9 -> 8 -> 7).
 - Step 5: Move up until the start of the first column excluding the visited element (7 -> 4).
 - Step 6: Continue spiraling inward (4 -> 5).
 - Step 7: All elements have been visited, return the spiral order.
 
 
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: 
    
- Step 1: Start at the top-left corner (1).
 - Step 2: Move right until the end of the first row (1 -> 2 -> 3 -> 4).
 - Step 3: Move down until the end of the last column (4 -> 8 -> 12).
 - Step 4: Move left until the start of the last row (12 -> 11 -> 10 -> 9).
 - Step 5: Move up until the start of the first column excluding the visited element (9 -> 5).
 - Step 6: Continue spiraling inward (5 -> 6 -> 7).
 - Step 7: All elements have been visited, return the spiral order.
 
 
Constraints
- m == matrix.length
 - n == matrix[i].length
 - 1 <= m, n <= 10
 - -100 <= matrix[i][j] <= 100
 - Time Complexity: O(m*n) where m is the number of rows and n is the number of columns
 - 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
- Use four pointers to keep track of the boundaries of the matrix.
 - Traverse the matrix in a spiral order by updating these boundaries after each traversal.
 - Use four different loops to traverse in four directions: right, down, left, and up.
 - After each direction change, update the corresponding boundary.
 - Continue until all elements are visited.