fork download
  1. System.in.readLines().each { input ->
  2. input = input as int
  3. def out = []
  4. def c = -1
  5. def r = 0
  6. def dir = [1,0]
  7. def steps = input
  8. def step = 0
  9. def edge = 0
  10.  
  11. (1..input*input).each {
  12. if (++step > steps) {
  13. step = 1
  14. dir = edge%2 ? dir.reverse()*.multiply(-1) : dir.reverse()
  15. if (++edge % 2) steps--
  16. }
  17. c += dir[0]
  18. r += dir[1]
  19. if (!out[r]) out[r] = []
  20. out[r][c] = it
  21. }
  22. println out*.collect{"$it".padLeft("${input*input}".length())}*.join(" ").join("\n") + "\n"
  23. }
Success #stdin #stdout 1.06s 4456448KB
stdin
4
5
stdout
 1  2  3  4
12 13 14  5
11 16 15  6
10  9  8  7

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