from collections import deque

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

def can_move(state, new_state, table):
    for x1, y1 in state:
        for dx in [-1, 0, 1]:
            for dy in [-1, 0, 1]:
                x2, y2 = x1 + dx, y1 + dy
                if (x2, y2) not in new_state and is_valid(x2, y2, len(table), len(table[0])):
                    if table[x2][y2] == '#':
                        return False
    return True

def slime_escape(n, m, table):
    target_state = {(n-2, m-2), (n-2, m-1), (n-1, m-2), (n-1, m-1)}
    initial_state = {(0, 0), (0, 1), (1, 0), (1, 1)}
    
    q = deque([(initial_state, 0)])
    visited = set()
    
    while q:
        state, steps = q.popleft()
        
        if state == target_state:
            return steps
        
        if state in visited:
            continue
        
        visited.add(state)
        
        for dx in [-1, 0, 1]:
            for dy in [-1, 0, 1]:
                new_state = set()
                for x, y in state:
                    new_x, new_y = x + dx, y + dy
                    new_state.add((new_x, new_y))
                
                if can_move(state, new_state, table):
                    q.append((new_state, steps + 1))
    
    return -1

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

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