from collections import deque
def is_valid_move(x, y, n, m, table):
    return 0 <= x < n and 0 <= y < m and table[x][y] == '.'
def min_transformations(n, m, table):
    start_state = (0, 0)  
    target_state = (n - 2, m - 2)  

    if start_state == target_state:
        return 0
    queue = deque()
    visited = set()
    queue.append(start_state)
    visited.add(start_state)

    while queue:
        x, y = queue.popleft()
        for dx in [-1, 0, 1]:
            for dy in [-1, 0, 1]:
                new_x, new_y = x + dx, y + dy

                if is_valid_move(new_x, new_y, n, m, table):
                    new_state = (new_x, new_y)

                    if new_state == target_state:
                        return len(visited)

                    if new_state not in visited:
                        visited.add(new_state)
                        queue.append(new_state)

    return -1

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

result = min_transformations(n, m, table)
print(result)

