Back to questions
Given an m x n matrix, return all elements of the matrix in spiral order.
In case you don’t think about spirals that often (unless you're pondering galaxies or those satisfying snail shells), here’s what we mean: start at the top-left corner and move right across the first row, then down the last column, left along the bottom row, and finally back up the first column. Keep spiraling inward until you’ve collected all the elements.
It’s like peeling layers off an onion… but way less tear-inducing!
Input: matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
![Spiral Matrix Example 1 DataLemur]
Input: matrix = [[1, 2, 3],[8, 9, 4],[7, 6, 5]]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
This approach involves rotating the input matrix so that the numbers we need always appear in the first row. Let's work through an example to understand this better:
The first three numbers () are in the first row of the matrix. We can extract them easily.
Once we extract the first row, the remaining matrix looks like this:
8 | 9 | 4 |
---|---|---|
7 | 6 | 5 |
Now the main question is: how do we get the rest of the numbers? Let's focus on getting the next two numbers (). Extracting them isn’t as straightforward as the first row, but what if we rotate the matrix counterclockwise? After rotating, it looks like this:
4 | 5 |
---|---|
9 | 6 |
8 | 7 |
Now, the next two numbers () are in the first row! We can extract them similarly to before. After removing the first row, the remaining matrix is:
9 | 6 |
---|---|
8 | 7 |
Do you notice the pattern? We are rotating the matrix counterclockwise so that the next numbers we need to extract are always in the first row. Each time we process a row, we remove it and rotate the remaining matrix.
If you haven't solved the Clockwise Matrix Rotation problem, you should do that first. In that problem, we rotate the matrix clockwise, but here we are rotating counterclockwise. You can either come up with a way to rotate the matrix counterclockwise or simply rotate the matrix clockwise three times to simulate a counterclockwise rotation.
Here is the full code:
This approach uses boundaries—top, bottom, left, and right—to traverse the matrix in a spiral order. Here's what each boundary represents:
Now, let's modify the previous approach:
Repeat this process until all elements have been added to the result.
Here’s the full code: