Print NxN spiral of ascending numbers The numbers should be printed with leading zeroes in a field with length = (number of digits of N^2).

Input (N): 

4


Output:

01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07


I am interested in the algorithm and the cleanliness of the implementation.
So, the white space does not count and the upper limit for N is 42.
Python

n=input()

matrix=[[j+1]*n for j in range(n)]

x=y=0
for i in range(n)[::-2]:
    x+=i*4;y+=1

    for j in range(i):
        matrix[j+y-1][y]=x+j

    matrix[y-1][y:y+i]=range(x,x-i,-1)

    R=matrix[n-y][y-1]+1
    matrix[n-y][y:n-y+1]=range(R,R+i)

    for j in range(y,y+i-1):
        matrix[j][n-y]=matrix[j-1][n-y]-1

for row in matrix:
    print ' '.join(`r`.zfill(len(`n*n`)) for r in row)



An approach that precalculate corner numbers. Eg, for 9x box, 32 56 72 80, which is (n-1)*4 where n is box sizes (9,7,5,3) in this case.
Right side of those numbers are 1-, and top to bottom is 1+, so basically generate from left to right, top to bottom, bottom to right, right to top side.




$ echo 9 | python codegolf-769-me.py
01 32 31 30 29 28 27 26 25
02 33 56 55 54 53 52 51 24
03 34 57 72 71 70 69 50 23
04 35 58 73 80 79 68 49 22
05 36 59 74 81 78 67 48 21
06 37 60 75 76 77 66 47 20
07 38 61 62 63 64 65 46 19
08 39 40 41 42 43 44 45 18
09 10 11 12 13 14 15 16 17


Other tests

$ echo 2 | python codegolf-769-me.py
1 4
2 3

$ echo 5 | python codegolf-769-me.py
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09

$ echo 10 | python codegolf-769-me.py
001 036 035 034 033 032 031 030 029 028
002 037 064 063 062 061 060 059 058 027
003 038 065 084 083 082 081 080 057 026
004 039 066 085 096 095 094 079 056 025
005 040 067 086 097 100 093 078 055 024
006 041 068 087 098 099 092 077 054 023
007 042 069 088 089 090 091 076 053 022
008 043 070 071 072 073 074 075 052 021
009 044 045 046 047 048 049 050 051 020
010 011 012 013 014 015 016 017 018 019