def isKadomatsu(a,b,c): if a == 0 or b == 0: return True return b < a < c or b < c < a or a < c < b or c < a < b dxdy=zip([-1,0,1,0],[0,1,0,-1]) W,H=map(int,raw_input().split()) M=[map(int,raw_input().split()) for i 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: w,h,bef=que.pop(0) if w==W-1 and h==H-1: print cost[bef][h][w] break cur=M[h][w] for dx,dy in dxdy: nw,nh=w+dx,h+dy if not (0<=nw