Solution: Spiral Matrix II
Let’s solve the Spiral Matrix II problem using the Matrices pattern.
We'll cover the following
Statement
Given a positive integer n
, create an
Constraints:
1
n
Solution
The essence of this solution lies in systematically filling an
Now, let’s look at the steps of the solution:
We initialize a matrix of size
with zeros and a counter, count
with. This matrix serves as the container for the spiral pattern and the counter to keep track of the current number to be placed in the matrix. We iterate through all the layers. The number of layers is calculated as
, which represents the number of complete iterations required to fill the matrix in a spiral order. Each layer is processed one at a time. For each layer, the matrix cells are filled in four specific directions:
Direction 1 (left to right): Traverse the top row of the current layer, filling the numbers from
layer
ton−layer
. We start from the leftmost cell of the current layer’s top row, traverse toward the right, and fill in the numbers. For example, in the first layer of amatrix, fill the first row with , , and . Direction 2 (top to bottom): Traverse the right column of the current layer, starting from the row below the top row(
layer+1
) to the bottom row of the current layer(n-layer
). Here, we traverse downwards, filling in the numbers. Continuing from the previous example, placeand in the right column. Direction 3 (right to left): Traverse the bottom row of the current layer, moving from the rightmost cell to the leftmost cell. Here, we start from the rightmost cell of the bottom row and traverse toward the left, filling in the numbers. This ensures the bottom row of the current layer is filled. For instance, place
and . Direction 4 (bottom to top): Traverse the left column of the current layer, moving upward from the cell below the bottom row to the cell above the top row. We start filling in the numbers upwards in the leftmost column. For example, place
.
At the end of the layer, all cells for that layer are filled in spiral order. For example,
The process is repeated for the next inner layer, if any, until the entire matrix is filled. For example, in the case of a
matrix, the inner layer (center cell) is filled as the final step. Once all layers are processed, the filled
matrix is returned.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.