from collections import deque def bfs(): dist = [[[-1]*4 for _ in range(W)] for _ in range(H)] q = deque([]) if M[0][0]!=M[0][1]: dist[0][1][0] = 1 q.append((0, 1, 0, 0, 0)) if M[0][0]!=M[1][0]: dist[1][0][1] = 1 q.append((1, 0, 0, 0, 1)) while q: cx, cy, px, py, f = q.popleft() for nx, ny, nf in [(cx, cy-1, 0), (cx-1, cy, 1), (cx, cy+1, 2), (cx+1, cy, 3)]: if not (0<=nxb and bc)): dist[nx][ny][nf] = dist[cx][cy][f]+1 q.append((nx, ny, cx, cy, nf)) return dist W, H = map(int, input().split()) M = [list(map(int, input().split())) for _ in range(H)] dist = bfs() ans = 10**18 for i in range(4): if dist[H-1][W-1][i]==-1: continue ans = min(ans, dist[H-1][W-1][i]) if ans==10**18: print(-1) else: print(ans)