Problem Description
Given a positive integer n, create an n x n matrix filled with elements from 1 to n² arranged in spiral order.
Key Insights
- Use four pointers (top, bottom, left, right) to keep track of the matrix boundaries.
- Traverse the matrix in a spiral: move right along the top row, then down the right column, left along the bottom row, and finally up the left column.
- Update the boundary pointers after each complete traversal of one side.
- Continue until all numbers from 1 to n² are filled into the matrix.
Space and Time Complexity
Time Complexity: O(n²)
Space Complexity: O(n²) (required for the output matrix)
Solution
We simulate the spiral movement by initializing four pointers: top, bottom, left, and right, which denote the current boundaries of the matrix that have not yet been filled. For each iteration, we:
- Traverse from left to right along the top boundary, then increment the top pointer.
- Traverse from top to bottom along the right boundary, then decrement the right pointer.
- If there are rows remaining, traverse from right to left along the bottom boundary, then decrement the bottom pointer.
- If there are columns remaining, traverse from bottom to top along the left boundary, then increment the left pointer. This algorithm ensures that the matrix is filled in a spiral order until all numbers are placed.