Spiral Matrix I
Simulation Array
Problem
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example:
Thought Process:
How do we know when we reach the end of one of the inner arrays inside the matrix?
By setting boundaries for top, bottom, left, and right. We update the boundaries when a row or column is complete.
How do we know when to go down, left, right, or up?
By having a variable representing the direction to go in. d = 0 (right), d = 1 (down), d = 2 (left), d = 3 (up)
How do we know when we reach the end of the spiral?
We have an outer while loop checking the boundaries. When the top boundary has passed the bottom boundary and when the left boundary has passed the right boundary, the loop will break.
Solution
Key Facts
The direction variable and boundary variables is what really helps solve this problem and are the main driving force for this solution.
We are essentially "shaving off" each row and column.
Time Complexity
Time: O(n) because we are going through every number in the matrix
Space: O(n) for the single array we are storing our solution in
Last updated
Was this helpful?