import sys from heapq import * def solve(): data = sys.stdin.buffer.read().split() H = int(data[0]); W = int(data[1]) grid = [data[i+2].decode() for i in range(H)] INF = float('inf') dist = {} pq = [] def relax(s, c): if dist.get(s, INF) > c: dist[s] = c heappush(pq, (c, s)) relax(('R', 0, 0, 1, 1), 0) while pq: d, s = heappop(pq) if d > dist.get(s, INF): continue t = s[0] if t == 'R': _, i, j, a, b = s if i == H-1 and j == W-1: print(d); return for di, dj in ((-1,0),(1,0),(0,-1),(0,1)): ni, nj = i+di, j+dj if 0 <= ni < H and 0 <= nj < W and grid[ni][nj] != '#': relax(('R', ni, nj, a, b), d+1) if a: if i > 0: relax(('VR', i-1, j, b), d+1) if i < H-1: relax(('VR', i, j, b), d+1) if b: if j > 0: relax(('VC', i, j-1, a), d+1) if j < W-1: relax(('VC', i, j, a), d+1) elif t == 'VR': _, r, j, b = s if j > 0: relax(('VR', r, j-1, b), d+1) if j < W-1: relax(('VR', r, j+1, b), d+1) if grid[r][j] != '#': relax(('R', r, j, 0, b), d+1) if grid[r+1][j] != '#': relax(('R', r+1, j, 0, b), d+1) if b: if j > 0: relax(('VX', r, j-1), d+1) if j < W-1: relax(('VX', r, j ), d+1) elif t == 'VC': _, i, c, a = s if i > 0: relax(('VC', i-1, c, a), d+1) if i < H-1: relax(('VC', i+1, c, a), d+1) if grid[i][c] != '#': relax(('R', i, c, a, 0), d+1) if grid[i][c+1] != '#': relax(('R', i, c+1, a, 0), d+1) if a: if i > 0: relax(('VX', i-1, c), d+1) if i < H-1: relax(('VX', i, c), d+1) else: # VX _, r, c = s if c > 0: relax(('VX', r, c-1), d+1) if c < W-1: relax(('VX', r, c+1), d+1) if r > 0: relax(('VX', r-1, c), d+1) if r < H-1: relax(('VX', r+1, c), d+1) for er, ej in [(r, c), (r, c+1), (r+1, c), (r+1, c+1)]: if 0 <= er < H and 0 <= ej < W and grid[er][ej] != '#': relax(('R', er, ej, 0, 0), d+1) print(-1) solve()