Introduction
Spiral Matrix means traversing all matrix elements in:
- spiral order
The traversal starts from:
- top row
- right column
- bottom row
- left column
and continues layer by layer.
Example:
Input Matrix:1 2 3
4 5 6
7 8 9
Output:
1 2 3 6 9 8 7 4 5
Explanation:
Matrix elementare visited in clockwise spiral order.This problem is one of the most important applications of:
Boundary Traversal Constraints
1 <= Rows, Columns <= 10^3 Approach 1 : Brute Force (Using Visited Matrix)
Explanations:
Explanation:
The idea is:
- move in spiral directions
- mark visited cells
Steps:
- Traverse right.
- Traverse down.
- Traverse left.
- Traverse up.
- Repeat until completed.
This approach works but:
- uses extra space
So boundary traversal is preferred.
Dry Run
Matrix:1 2 3
4 5 6
7 8 9
Spiral Order:
1 2 3
6 9 8 7 4 5
Practice :
Complexity Analysis :
Time Complexity:- O(rows × cols)Explanation : Every matrix element is visited once.
Space Complexity:- O(rows × cols)
Explanation :
Visited matrix is used.
Approach 2 : Optimal Solution(Boundary Traversal)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- maintain boundaries
- shrink boundaries after traversal
Boundaries:
- top
- bottom
- left
- right
This avoids:
- extra visited matrix
Dry Run
Matrix:1 2 3
4 5 6
7 8 9
Top row:
1 2 3
Right column:
6 9
Bottom row:
8 7
Left column:
4
Center:
5
Practice :