See the original problem on HackerRank.
A bunch of villains are waiting in line for being accepted on board of the Queen Anne’s Revenge, docked somewhere in Nassau, to become part of the crew. Every rascal is represented by a number corresponding to the “pieces of eight” they have stolen so far.
However, the pirates of the Queen Anne’s Revenge are as crazy as the captain and arrange that line in a spiral:
Rascals that make it wrong will walk the plank!
We want to help them by writing an algorithm that prints the line from the outermost villain to the innermost. In other words, we want to print a matrix in clockwise order starting from the top left corner. For the example above, the expected output is:
1 2 3 4 8 12 11 10 9 5 6 7
Arrr!
Input Format
 the first line contains \( N \) (number of rows) and \( M \) (number of columns).
 then, \( N \) lines that contain \( M \) numbers each.
Constraints
 \( 1 \leq N \leq 100 \)
 \( 1 \leq M \leq 100 \)
 every number of the matrix is a 32bit integer
Output Format
The elements of the matrix printed in a clockwise spiral order, spaceseparated.
Solutions
One solution consists in traversing the matrix left to right, then top to bottom, then right to left, then bottom to top, then repeat until we have done. Every time, the boundaries are updated. For example, when traversing from left to right, we are basically “cutting” the upper border of the matrix:


After visiting 1 2 3 4
, the matrix turns into:


Then we visit the matrix from top to bottom:


And the matrix turns into:


And so on.
The core part of this problem is about updating indexes. If you don’t mess them up, you solve this problem easily.
Here is a C++ solution:


From here, we can even make the solution more concise and generic by introducing a sort of direction vector that contains the offsets of all the directions to take:


For example, [0, 1]
means left to right: 0
represents the steps on the row axis, 1
on the column axis.
Here is the complete solution in C++:


In addition to being more succinct, this solution is more generic and allows us to change direction easily. For instance, the only things to change in order to visit the matrix in counterclockwise order are:


and

