from collections import defaultdict as D 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 xrange(H)];dxy=((1,0),(0,1),(-1,0),(0,-1)) C=[[D(lambda:W*H+1)for i in xrange(W)]for i in xrange(H)];Q=[] for x,y in dxy[:2]:A=(M[0][0],M[y][x]);C[y][x][A]=1;Q+=[(1,(x,y),A)] while Q: c,h,A=heappop(Q) if h==G:print c;break for dx,dy in dxy: nx=h[0]+dx;ny=h[1]+dy if 0<=nx