import heapq bit10 = (1 << 10) - 1 def solve(h, w, a): col = [[-1] * w for _ in range(h)] ans = 0 num = (a[0][0] << 20) | 0 queue0 = [num] num = (a[h-1][w-1] << 20) | (h-1 << 10) | w-1 queue1 = [num] while True: ans += 1 filled = False while True: if queue0: num = heapq.heappop(queue0) i = (num >> 10) & bit10 j = num & bit10 if col[i][j] != -1: continue filled = True col[i][j] = 0 for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]: ni, nj = i + di, j + dj if ni < 0 or ni >= h or nj < 0 or nj >= w: continue if col[ni][nj] == 0: continue elif col[ni][nj] == 1: return ans - 2 else: num = (a[ni][nj] << 20) | (ni << 10) | nj heapq.heappush(queue0, num) if filled: break ans += 1 while True: if queue1: num = heapq.heappop(queue1) i = (num >> 10) & bit10 j = num & bit10 if col[i][j] != -1: continue filled = True col[i][j] = 1 for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]: ni, nj = i + di, j + dj if ni < 0 or ni >= h or nj < 0 or nj >= w: continue if col[ni][nj] == 1: continue elif col[ni][nj] == 0: return ans - 2 else: num = (a[ni][nj] << 20) | (ni << 10) | nj heapq.heappush(queue1, num) if filled: break def main(): h, w = [int(x) for x in input().split()] a = [[int(x) for x in input().split()] for _ in range(h)] print(solve(h, w, a)) if __name__ == "__main__": main()