Code Help - Fill a mXn 2D matrix layer by layer

How to fill a mXn 2D matrix layer by layer from outer-most to inner-most. I want a matrix like this e.g. 4X6 matrix (matrix is always a rectangle)
11 12 13 14 15 16
26 27 28 29 30 17
25 34 33 32 31 18
24 23 22 21 20 19

The matrix is being filled in the sequence of numbers strting from 11. And I want to follow the same path as 11 then 12 then 13…ans so on…till 34

Please help me with the commented and well explained code. Thank you in advance.

You can just simulate the process as you would do it manually. Initially fill the matrix with zeroes. Maintain four variables a, i, j and direction. For direction%4==0 increment j each step, for 1, increment i, for 2, decrement j and for 3, decrement i. If the next cell is already filled or does not exist, increment the direction. Assign ans[i][j]=a and increment a each step.

1 Like

loop until half of min( m , n ) {
different loops for up right down left

1 Like

got it. thanks