from heapq import heappop,heappush I=lambda:map(int,raw_input().split());W,H=I();G=(W-1,H-1) M=[I()for i in range(H)];dxy=((1,0),(0,1),(-1,0),(0,-1)) C=[[[W*H+1]*10 for i in range(W)]for i in range(H)];Q=[] for x,y in dxy[:2]:C[y][x][M[0][0]]=1;Q+=[(1,(x,y),M[0][0])] while Q: c,h,b=heappop(Q) if h==G:print c;break t=M[h[1]][h[0]];nc=c+1 for dx,dy in dxy: nx=h[0]+dx;ny=h[1]+dy if 0<=nx