def dist(start, goal): return abs(start[0]-goal[0]) + abs(start[1]-goal[1]) - 1 def gather_blanks(start_blank): blanks = set([(start_blank[0], start_blank[1])]) queue = [(start_blank[0], start_blank[1])] while queue: cur = queue.pop(0) if cur[0] < (H-2) and wall[cur[0]+1][cur[1]] == ".": if not ((cur[0]+1, cur[1]) in blanks): queue.append((cur[0]+1, cur[1])) blanks.add((cur[0]+1, cur[1])) if cur[1] < (W-2) and wall[cur[0]][cur[1]+1] == ".": if not ((cur[0], cur[1]+1) in blanks): queue.append((cur[0], cur[1]+1)) blanks.add((cur[0], cur[1]+1)) if cur[0] > 2 and wall[cur[0]-1][cur[1]] == ".": if not ((cur[0]-1, cur[1]) in blanks): queue.append((cur[0]-1, cur[1])) blanks.add((cur[0]-1, cur[1])) if cur[1] > 2 and wall[cur[0]][cur[1]-1] == ".": if not ((cur[0], cur[1]-1) in blanks): queue.append((cur[0], cur[1]-1)) blanks.add((cur[0], cur[1]-1)) return blanks W, H = map(int, input().split(" ")) wall = [] for i in range(H): wall.append(list(input())) start_blank = [-1,-1] for i in range(H): if wall[i].count(".") > 0: start_blank[0] = i start_blank[1] = wall[i].index(".") break blanks_1 = gather_blanks(start_blank) start_blank = [-1,-1] for i in range(H): if wall[i].count(".") == 0: continue start_blank[0] = i for j in range(W): if wall[i][j] == "." and not ((i, j) in blanks_1): start_blank[1] = j break if start_blank[1] != -1: break blanks_2 = gather_blanks(start_blank) blanks_1 = list(blanks_1) blanks_2 = list(blanks_2) ans = max(H, W) for b in range(len(blanks_1)): for s in range(len(blanks_2)): ans = min(ans, dist(blanks_1[b], blanks_2[s])) print(ans)