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.
xxxxxxxxxx
20
Method: traverse
Input: mxn matrix
​
Initialize:
1. rowLower = 0
2. rowUpper = m-1
3. colLower = 0
4. 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