Generate a Spiral Matrix
This challenge asks you to create a square matrix filled with integers from 1 to n*n in a spiral order. This is a classic problem that tests your ability to manage boundaries and directions within a 2D grid, a fundamental skill in many algorithmic tasks.
Problem Description
Given an integer n, you need to generate an n x n 2D matrix filled with elements from 1 to n*n in a spiral order. The spiral should start from the top-left corner, move right, then down, then left, then up, and continue inwards.
Key Requirements:
- The matrix must be of size
n x n. - The matrix should be populated with integers from 1 up to
n*n, inclusive. - The population must follow a clockwise spiral pattern.
Expected Behavior: The algorithm should correctly fill the matrix according to the spiral traversal rules.
Edge Cases to Consider:
n = 1: A single-element matrix.nis an even number.nis an odd number.
Examples
Example 1:
Input: n = 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Explanation:
The numbers are filled in the following order:
1 -> 2 -> 3 (right)
4 -> 5 (down)
6 -> 7 (left)
8 (up)
9 (center)
Example 2:
Input: n = 1
Output:
[
[ 1 ]
]
Explanation:
For n=1, the matrix contains only the number 1.
Example 3:
Input: n = 4
Output:
[
[ 1, 2, 3, 4 ],
[ 12, 13, 14, 5 ],
[ 11, 16, 15, 6 ],
[ 10, 9, 8, 7 ]
]
Explanation:
Similar spiral traversal as in Example 1, but for a larger grid.
Constraints
1 <= n <= 20nis an integer.- The solution should be efficient, aiming for a time complexity that is linear with respect to the number of elements in the matrix (
O(n*n)).
Notes
Think about how you can systematically traverse the matrix while keeping track of the boundaries of the current spiral layer. You'll need to manage the current direction of movement and when to change it. Consider using variables to represent the boundaries of the unvisited portion of the matrix.