from queue import Queue def bfs(y, x, C, cave, num): Q = Queue() Q.put((y, x)) while not Q.empty(): n = Q.get() if C[n[0]][n[1]-1] == '.' and (n[0], n[1]-1) not in cave[num]: cave[num].append((n[0], n[1]-1)) Q.put((n[0], n[1]-1)) if C[n[0]][n[1]+1] == '.' and (n[0], n[1]+1) not in cave[num]: cave[num].append((n[0], n[1]+1)) Q.put((n[0], n[1]+1)) if C[n[0]-1][n[1]] == '.' and (n[0]-1, n[1]) not in cave[num]: cave[num].append((n[0]-1, n[1])) Q.put((n[0]-1, n[1])) if C[n[0]+1][n[1]] == '.' and (n[0]+1, n[1]) not in cave[num]: cave[num].append((n[0]+1, n[1])) Q.put((n[0]+1, n[1])) return W, H = map(int, input().split()) C = [] for _ in range(H): C.append(input()) num = 0 cave = [[],[]] for y in range(1, H-1): for x in range(1, W-1): if C[y][x] == '.' and (y, x) not in cave[0] and (y, x) not in cave[1]: cave[num].append((y, x)) bfs(y, x, C, cave, num) num += 1 min_dist = float('inf') for c1 in cave[0]: for c2 in cave[1]: min_dist = min(min_dist, abs(c1[0] - c2[0]) + abs(c1[1] - c2[1]) - 1) print(min_dist)