H,W=map(int, input().split()) A=[];B=[];D={} for i in range(H): AA=list(map(int, input().split())) A.append(AA) for j in range(W): a=AA[j] if a not in D: D[a]=[] B.append(a) D[a].append((i,j)) B=sorted(B) dp=[[1]*W for _ in range(H)] dy,dx=[1,-1,0,0],[0,0,1,-1] for b in B: if b==1: continue for y,x in D[b]: for i in range(4): ny,nx=y+dy[i],x+dx[i] if 0<=ny