Imagine you are walking through a dungeon and you want to find the destination point in the middle.
That’s right…printing values in a spiral matrix feels like that.
To give you some context, let’s say we have the following double array arr:
As you can see, the numbers spirals 1 to 25 from the outer layers, left to right, top to bottom, right to left, and bottom to up as it dives across other inner layers in a similar passion.
The question is, how do we traverse the whole array in a spiral manner and print them in the right format?
Here is my suggested solution:
- Step 1: have a row begin and row-end count, column begin, and column end count. These counts will be used to track boundaries and conditions to end looping through the matrix.
- Step 2: add items going from top row, left to right. Afterward, increment row begin count.
- Step 3: add items on the rightmost column, from top to bottom. Afterward, decrement column end count.
- Step 4: Check if row begin is less than or equal to row end count. This is to prevent adding/printing existing elements that have already been traversed. If the condition matches, then we traverse on the current column end count(on the first iteration, this will be iterating on the last row, going from right column to the leftmost column) until it hits columnBegin count.
- Step 5:check if the column begins is less than or equal to columned count. This is to prevent adding/printing existing elements that have already been traversed. If the condition matches, then we traverse on the current row end count(on the first iteration, this will be iterating on left-most column, going from bottom to up on the same column) until it hits rowBegin count.
Here is the implementation for the algorithm:
That’s it! You just learned how to solve the spiral matrix problem.