To print a two-dimensional array (matrix) in spiral order, you can follow this algorithmic approach.
-
Initialize Boundaries: Set
top
,bottom
,left
, andright
to define the current boundaries of the matrix. - Spiral Traversal:
- Traverse from left to right across the
top
row, then incrementtop
. - Traverse from the top to bottom down the
right
column, then decrementright
. - If there are remaining rows, traverse from right to left across the
bottom
row, then decrementbottom
. - If there are remaining columns, traverse from bottom to top up the
left
column, then incrementleft
. - Repeat: Continue this process until all elements are printed.
This algorithm works for any size matrix and allows you to print the elements in spiral order.