Given a matrix (2D array) of m x n elements (m rows, n columns), write a function that prints the elements in the array in a spiral manner.
If you have done enough training by now, you would have immediately recognized the sub-problems within this problem. When you recognize this property, then you know that this problem is easily solvable with recursion!
Imagine that you are peeling an onion (I know your eye hurts!). First, you peel off the outer-layer skin. After the first layer is peeled off, there’s another layer to peel. So you peel off the remaining onion again until there is no more to peel, which is where you stop.
It’s the same with printing the matrix spirally! Print the outer layer of the matrix, then print the remaining sub-matrix recursively. Please do not forget to handle the base case! (Hint: Check when m == 1 or n == 1).
Read full article from Printing Matrix (2D array) in Spiral Order | LeetCode
No comments:
Post a Comment