0

In this question: Looping in a spiral outside-in, there is a way to "extract the values spirally in a matrix". But what if the requirement is, given an empty n × m matrix, populate it so that it looks something like:

[
  [ 1, 2, 3, 4,],
  [12,13,14, 5,],
  [11,16,15, 6,],
  [10, 9, 8, 7,]
]

(so the above is matrix is, given a 4 × 4 matrix, with all 0s in it, and now populate this matrix so that it looks like the above matrix. Then is there a way like the recursive answer as in Looping in a spiral outside-in ? (Although my concern also is: that solution is elegant, but it is not O(n*m))

Community
  • 1
  • 1
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • Hope it helps: http://rosettacode.org/wiki/Spiral_matrix – notbad Nov 20 '15 at 02:27
  • see [Print 2-D Array in clockwise expanding spiral from center](http://stackoverflow.com/a/33688562/2521214) just use/generate the turtle command string in reverse – Spektre Nov 20 '15 at 08:05

1 Answers1

0

Not particularly elegant, but it's easy to keep track of the next four coordinates where you'll turn (i.e., start placing elements in a different direction) and to cycle through the four directions. Each time you come to a turn, you replace it with the coordinate 1 towards the center of the matrix on both axes (which is where your next turn for that corner will be) and switch to the next direction.

Dave
  • 7,460
  • 3
  • 26
  • 39