Example 72: Access 2-D Array Elements in a Spiral

Learn how to access elements of a matrix in a spiral manner.

Problem

Given a 2-D array of size 4 x 4, write a function to visit all its elements in a spiral fashion.

Example

Input Output
1   2   3  4
5   6   7   8
9  10 11 12
13 14 15 16
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Try it yourself

Try to solve this question on your own in the code widget below. If you get stuck, you can always refer to the solution provided.

Get hands-on with 1400+ tech skills courses.