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,0]] while que: [x,y,bfr,count]=que.pop(0) cur=M[y][x] if x==W-1 and y==H-1: print count exit() for dx,dy in dxdy: nx,ny=x+dx,y+dy if not(0<=nx