Print a given matrix in spiral form
Problem
Given a 2D array, print it in spiral form.
Input: {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16 }}
Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Explanation: The output is a matrix in a spiral format.
Input: { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}}
Expected output:
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
Explanation: The output is a matrix in a spiral format.
First, I considered solving this problem by defining the prescriptive rule on which direction to go and how much to go by observing the sample problem. However, I found that the code gets overly complicated if we go that path.
I decided to think of this problem as the DPS problem where we search through the matrix in a specified direction until we reach the end before switching direction.
This made the problem much easier and I don't have to think about the corner case much.
This can be solved in $O(N * M)$ where N is the width of the matrix and M is the height of the matrix.
UPDATE (2023-03-03): solution in python
Practice statistics:
15 mins: to come up with the algorithm
28 mins: to write the code and review the code.
Comments
Post a Comment