class DisjointSet(object): def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n self.num = n # number of disjoint sets def union(self, x, y): self._link(self.find_set(x), self.find_set(y)) def _link(self, x, y): if x == y: return self.num -= 1 if self.rank[x] > self.rank[y]: self.parent[y] = x else: self.parent[x] = y if self.rank[x] == self.rank[y]: self.rank[y] += 1 def find_set(self, x): xp = self.parent[x] if xp != x: self.parent[x] = self.find_set(xp) return self.parent[x] def read_data(): W, H = map(int, input().split()) maze = [input().strip() for h in range(H)] return W, H, maze import collections def solve(W, H, maze): maze = [[c == '.' for c in row] for row in maze] djs = DisjointSet(W * H) for h in range(1, H-1): for w in range(1, W-1): pos = h * W + w if maze[h][w]: if maze[h-1][w]: djs.union(pos, pos - W) if maze[h][w-1]: djs.union(pos, pos - 1) else: djs.union(pos, 0) areas = collections.defaultdict(list) for h in range(1, H-1): for w in range(1, W-1): p = djs.find_set(h * W + w) if p: areas[p].append((h, w)) a1, a2 = areas frontiers = areas[a1] dist = 0 while frontiers: new_frontiers = [] for (h, w) in frontiers: for nh, nw in [(h+1, w), (h-1, w), (h, w+1), (h, w-1)]: if nh < 0 or nh >= H or nw < 0 or nw >= W: continue if djs.find_set(nh * W + nw) == a2: return dist elif not maze[nh][nw]: maze[nh][nw] = True new_frontiers.append((nh, nw)) frontiers = new_frontiers dist += 1 if __name__ == '__main__': W, H, maze = read_data() print(solve(W, H, maze))