from heapq import heappop,heappush I=lambda:map(int,raw_input().split());W,H=I() M=[I()for i in range(H)];D=((1,0),(0,1),(-1,0),(0,-1)) C=[[10*[W*H]for i in range(W)]for i in range(H)];Q=[] for x,y in D[:2]:m=M[0][0];C[y][x][m]=1;Q+=[(1,x,y,m)] while Q: c,x,y,b=heappop(Q) if(W-x)*(H-y)==1:print c;break t=M[y][x];d=c+1 for u,v in D: z=x+u;w=y+v if 0<=z