M[0,0]=1;
M[i_,j_]:=If[i≤j,If[i+j≥0,If[i≠j,M[i+1,j]+1,M[i,j-1]+1],M[i,j+1]+1],If[i+j>1,M[i,j-1]+1,M[i-1,j]+1]]
M[n_]:=n^2+1-If[EvenQ[n],Table[M[i,j],{j,n/2,-n/2+1,-1},{i,-n/2+1,n/2}],Table[M[i,j],{j,(n-1)/2,-(n-1)/2,-1},{i,-(n-1)/2,(n-1)/2}]];

{u,r,v}=SmithDecomposition[M[30]];r//Diagonal