As this smells like homework then no code or direct answer instead just few hints:
You can look at this as an turtle problem:
Let m
be movement by 1
cell and r
be rotation by 90
degrees in your spiral direction (CW or CCW). then the spiral can be encoded as series of turtle commands forming this pattern (from the start point):
m,r,m,r,
m,m,r,m,m,r,
m,m,m,r,m,m,m,r,
m,m,m,m,r,m,m,m,m,r,
m,m,m,m,m,r
As you can see you start with 1x move then rotate after two repetition you switch to 2x move, after 2 moves switch to 3x move,... and so on. This can be done with just few for loops (or just by one with some proper iterations and stopping when matrix number of cells is hit ... or the endpoint corner is hit)
You need to handle even/odd matrix sizes
for odd matrix sizes is the middle point easy. For even sizes it is a bit more complicated. if you use CW rotation then use the rounded down division result of halving the size and start with moving to the right. (if you need different spiral then you need to add +1
to x
and/or y
and change starting direction) so the spiral will stay centered.
So If you got even sized matrix then the last movement is twice if you got odd size then the last movement is there just once (like in this example)
rotation
Have direction stored as 2D vector. for example d=(+1,0)
means right. to rotate 2D vector you just swap coordinates and negate one axis (which one means the CW/CCW). For example (x,y) -> (y,-x)
movement
Store current position as 2D vector too. The movement is just adding current direction vector to it.
Have fun with solving this ...