dxdy=zip([-1,0,1,0],[0,1,0,-1]) def kadomatsu(a,b,c): if a==0 or b==0: return True else: if (a!=b and b!=c and c!=a) and not (ab>c): return True else: return False W,H=map(int,raw_input().split()) M=[map(int,raw_input().split()) for _ in xrange(H)] que=[[0,0,0]] cost=[[[-1]*W for _ in xrange(H)] for i in xrange(10)] cost[0][0][0]=0 while que: [bef,x,y]=que.pop(0) cur=M[y][x] if x==W-1 and y==H-1: print cost[bef][y][x] exit() for dx,dy in dxdy: nx,ny=x+dx,y+dy if not(0<=nx