from collections import deque

def is_valid(x, y, n, m):
    return 0 <= x < n and 0 <= y < m

def can_escape_slime(table):
    n, m = len(table), len(table[0])
    start = [(0, 0), (0, 1), (1, 0), (1, 1)]  # Начальное состояние слайма
    end = [(n-2, m-2), (n-2, m-1), (n-1, m-2), (n-1, m-1)]  # Конечное состояние слайма
    visited = set()
    queue = deque([(start, 0)])

    while queue:
        current, moves = queue.popleft()
        if current == end:
            return moves

        for dx in [-1, 0, 1]:
            for dy in [-1, 0, 1]:
                next_state = [(x + dx, y + dy) for x, y in current]
                if all(is_valid(x, y, n, m) and table[x][y] != '#' for x, y in next_state) and tuple(next_state) not in visited:
                    visited.add(tuple(next_state))
                    queue.append((next_state, moves + 1))

    return -1  # Не удалось найти путь

n, m = map(int, input().split())
table = [list(input().strip()) for _ in range(n)]
result = can_escape_slime(table)
print(result)
