R=range J=lambda:map(int,input().split()) N,M=J() A=list(J()) P=[] V=N*M+N E=[] for v in R(V): i,j,e=v//N,v%N,[] if i:a,n=A[i-1],i*N-N;e+=[[n+(a if j==a-1else a-1if j==a else j),0]] if j:e+=[[i*N+j-1,1]] if j+1W[i]:continue for[j,v]in E[i]: u=w+v if u