import qualified Data.Set as S import Data.List manhattan (x1,y1) (x2,y2) = abs (x1-x2) + abs (y1-y2) nub' = S.toList . S.fromList untilFix f x = if f x == x then x else untilFix f (f x) reachable ps p = untilFix move [p] where move = nub' . concatMap neighbor neighbor (x,y) = intersect [(x,y),(x+1,y),(x-1,y),(x,y+1),(x,y-1)] ps main = getContents >>= print . twohole . lines twohole (wh:m) = minimum (manhattan <$> h1 <*> h2) - 1 where [w,h] = map read (words wh) hs = [(x,y) | x<-[1..w-2], y<-[1..h-2], m!!y!!x == '.'] (h1,h2) = let hs' = reachable hs (head hs) in (hs', hs\\hs')