:- use_module(contestlib, [writeN/2, for/3, int_width/2, write_int/2]).
spiral(N,M) :-
NM is N*M,
int_width(NM,Width),
Width1 is Width + 1,
for(I,1,N),
nl,
for(J,1,M),
distance(N,M,I,J,Distance),
write_int(Distance,Width1),
fail.
spiral(_,_).
distance(_,_,1,J,D) :- !, D is J - 1 + 1.
distance(_,M,I,M,D) :- !, D is M + I - 2 + 1.
distance(N,M,N,J,D) :- !, D is N + 2*M - J - 2 + 1.
distance(N,M,I,1,D) :- !, D is 2*N + 2*M - I - 3 + 1.
distance(N,M,I,J,D) :-
N1 is N - 2,
M1 is M - 2,
I1 is I - 1,
J1 is J - 1,
distance(N1,M1,I1,J1,D1),
D is 2*N + 2*M + D1 - 4.