import Control.Applicative import Control.Monad import Data.Maybe (fromJust) import Text.Printf import Data.Array import Debug.Trace type Pos = (Int,Int) type Map = Array Pos Char around (y,x) = [(y,x+1), (y,x-1), (y+1,x), (y-1,x)] main = do [w,h] <- map (read :: String->Int) . words <$> getLine xs <- getContents let m = listArray ((0,0),(h-1,w-1)) $ filter (/='\n') xs print $ solve $ part m (0,0) h w part :: Map -> Pos -> Int -> Int -> [[Pos]] part m (y,x) h w | y == h = [] | x == w = part m (y+1,0) h w | otherwise = if (m!(y,x)) == '.' then pss : part m' (y,x+1) h w else part m (y,x+1) h w where (m',pss) = fill m (y,x) fill :: Map -> Pos -> (Map, [Pos]) fill m p | m!p == '#' = (m, []) | otherwise = let (m1,ps1) = fill after (ap!!0) (m2,ps2) = fill m1 (ap!!1) (m3,ps3) = fill m2 (ap!!2) (m4,ps4) = fill m3 (ap!!3) in (m4,[p]++ps1++ps2++ps3++ps4) where after = m // [(p,'#')] ap = around p solve [ps1,ps2] = (+(-1)) $ minimum $ map (\p1-> minimum $ map (dist p1) ps2) ps1 dist (y1,x1) (y2,x2) = abs (y1 - y2) + abs (x1 - x2)