Spiral Matrix II
Simulation Array
Problem
Given a positive integer n, generate a square matrix filled with elements from 1 to in spiral order.
For example:
Thought Process
How would we go about changing the directions when filling the 2D matrix?
Have a variable d for the direction and updating this variable whenever we "shave" off a row or column.
How would we generate the numbers to fill the 2D matrix from 1 to .
Have a varaible called num initially set 1, incrementing this variable at each cell, and filling each cell with the variable.
Solution
Key Facts
The direction and boundary variables are most important
For updating the number, just have a num variable and increment by 1 in the for-loops
With each direction, there is either a constant row or column (i.e. when doing in the down direction, the constant is the right column.)
Time Complexity
Time: O() because we have to fill every row and column
Space: O() because we are initilizing a matrix and storing the numbers here.
Last updated