import sys from collections import deque def solve(): input = sys.stdin.read data = input().split() if not data: return H = int(data[0]) W = int(data[1]) grid = data[2:] new_h = 2 * H - 1 new_w = 2 * W - 1 # We don't explicitly need to build the 2D array of the expanded grid. # We can determine if a coordinate is a wall '#' mathematically to save memory/time. # (r, c) represents coordinates in the expanded grid. def is_wall(r, c): if r % 2 == 0 and c % 2 == 0: return grid[r // 2][c // 2] == '#' return False dist = [[-1] * new_w for _ in range(new_h)] q = deque() q.append((0, 0)) dist[0][0] = 0 dr = [-1, 1, 0, 0] dc = [0, 0, -1, 1] while q: r, c = q.popleft() if r == new_h - 1 and c == new_w - 1: print(dist[r][c]) return current_d = dist[r][c] for d in range(4): nr = r + dr[d] nc = c + dc[d] if 0 <= nr < new_h and 0 <= nc < new_w: if not is_wall(nr, nc): if dist[nr][nc] == -1: dist[nr][nc] = current_d + 1 q.append((nr, nc)) print(-1) if __name__ == '__main__': solve()