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:] # Types of states: # 0: In a regular grid cell (r, c) # 1: On a horizontal highway between row r and r+1, at column c # 2: On a vertical highway between col c and c+1, at row r # 3: At the intersection of horizontal highway r and vertical highway c # We flatten the states into a 1D array to optimize Python array access times # state_id = (r * W + c) * 4 + type num_states = H * W * 4 dist = [-1] * num_states start_state = 0 # (0, 0, 0) dist[start_state] = 0 dq = deque([start_state]) while dq: u = dq.popleft() d_u = dist[u] type_ = u % 4 rem = u // 4 c = rem % W r = rem // W if r == H - 1 and c == W - 1 and type_ == 0: print(d_u) return # Helper to push states into the deque def push(nr, nc, ntype, cost): nu = (nr * W + nc) * 4 + ntype if dist[nu] == -1 or dist[nu] > d_u + cost: dist[nu] = d_u + cost if cost == 0: dq.appendleft(nu) else: dq.append(nu) if type_ == 0: # Type 0: Normal Grid Cell # Move to adjacent normal cells if r > 0 and grid[r - 1][c] != '#': push(r - 1, c, 0, 1) if r < H - 1 and grid[r + 1][c] != '#': push(r + 1, c, 0, 1) if c > 0 and grid[r][c - 1] != '#': push(r, c - 1, 0, 1) if c < W - 1 and grid[r][c + 1] != '#': push(r, c + 1, 0, 1) # Enter Highways if r < H - 1: push(r, c, 1, 1) # Below if r > 0: push(r - 1, c, 1, 1) # Above if c < W - 1: push(r, c, 2, 1) # Right if c > 0: push(r, c - 1, 2, 1) # Left elif type_ == 1: # Type 1: Horizontal Highway # Leave highway push(r, c, 0, 1) push(r + 1, c, 0, 1) # Move along highway if c > 0: push(r, c - 1, 1, 1) if c < W - 1: push(r, c + 1, 1, 1) # Enter intersections if c < W - 1: push(r, c, 3, 1) if c > 0: push(r, c - 1, 3, 1) elif type_ == 2: # Type 2: Vertical Highway # Leave highway push(r, c, 0, 1) push(r, c + 1, 0, 1) # Move along highway if r > 0: push(r - 1, c, 2, 1) if r < H - 1: push(r + 1, c, 2, 1) # Enter intersections if r < H - 1: push(r, c, 3, 1) if r > 0: push(r - 1, c, 3, 1) elif type_ == 3: # Type 3: Intersection # Leave intersection push(r, c, 1, 1) push(r, c + 1, 1, 1) push(r, c, 2, 1) push(r + 1, c, 2, 1) print("-1") if __name__ == '__main__': solve()