Traversing the Outer Edges
To traverse the outer edge, we have to follow the given sequence:
- Move right
- Move down
- Move left
- Move up
Once we have moved entirely right, we can increment rowLower. Similarly, once we have traversed down the right-most column we can decrement colUpper. Therefore, to traverse the entire matrix in spiral order, we can follow the given algorithm.
The entire process is shown in the figure below:

Here, we share some pseudo-code to help make sense of the logic involved.
xxxxxxxxxx20
Method: traverseInput: mxn matrix​Initialize: 1. rowLower = 02. rowUpper = m-13. colLower = 04. colUpper = n-1​while the entire matrix is not traversed repeat{ i. Traverse the row with index rowLower ii. rowLower ++ iii. Traverse the column with index colUpper iv. colUpper -- v. Traverse the row with index rowUpper vi. rowUpper -- vii. Traverse the column with index colLower viii. colLower ++}OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


