Pybites Logo

Code your way out of a grid

Level: Advanced (score: 4)

Given a 2D grid of equal length x and y, can you print the route to go from 1 to n? For example:

21 - 22 - 23 - 24 - 25
 |
20    7 -  8 -  9 - 10
 |    |              |
19    6    1 -  2   11
 |    |         |    |
18    5 -  4 -  3   12
 |                   |
17 - 16 - 15 - 14 - 13

You can assume the start value is 1 and it's in the center. Now print the sequences separated by the direction changes like so:

1 2 ⇓
3 ⇐
4 5 ⇑
6 7 ⇒
8 9 10 ⇓
11 12 13 ⇐
14 15 16 17 ⇑
18 19 20 21 ⇒
22 23 24 25

Thanks Martin for the idea, we learned quite a bit ourselves, redesigning/refactoring our solution.