import sys import heapq from collections import deque def main(): input = sys.stdin.read().split() idx = 0 W = int(input[idx]) idx += 1 H = int(input[idx]) idx += 1 grid = [] for _ in range(H): line = input[idx] grid.append(list(line)) idx += 1 visited = [[False for _ in range(W)] for _ in range(H)] regions = [] for y in range(H): for x in range(W): if grid[y][x] == '.' and not visited[y][x]: queue = deque() queue.append((x, y)) visited[y][x] = True current_region = [] while queue: cx, cy = queue.popleft() current_region.append((cx, cy)) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: nx = cx + dx ny = cy + dy if 0 <= nx < W and 0 <= ny < H and not visited[ny][nx] and grid[ny][nx] == '.': visited[ny][nx] = True queue.append((nx, ny)) regions.append(current_region) region_A = regions[0] region_B = regions[1] region_b_set = set((x, y) for (x, y) in region_B) INF = float('inf') distance = [[INF for _ in range(W)] for _ in range(H)] heap = [] for (x, y) in region_A: distance[y][x] = 0 heapq.heappush(heap, (0, x, y)) dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] while heap: current_cost, x, y = heapq.heappop(heap) if (x, y) in region_b_set: print(current_cost) return if current_cost > distance[y][x]: continue for dx, dy in dirs: nx = x + dx ny = y + dy if 0 <= nx < W and 0 <= ny < H: new_cost = current_cost + (1 if grid[ny][nx] == '#' else 0) if new_cost < distance[ny][nx]: distance[ny][nx] = new_cost heapq.heappush(heap, (new_cost, nx, ny)) if __name__ == "__main__": main()