import Control.Monad (replicateM) import Data.List (sort) distance :: (Int, Int) -> (Int, Int) -> Double distance a b = sqrt $ distance2 a b distance2 :: (Int, Int) -> (Int, Int) -> Double distance2 a b = x2 + y2 where x2 = (fromIntegral (fst a) - fromIntegral (fst b)) ** 2 y2 = (fromIntegral (snd a) - fromIntegral (snd b)) ** 2 solve :: [(Int, Int)] -> [(Int, Int)] -> [Double] solve [] _ = [] solve (w:ws) ms = d : solve ws ms where d = foldr (\x y -> distance w x + y) 0.0 ms getWaku w h = [ (x, 0) | x <- [1..w] ] ++ [ (0, y) | y <- [1..h] ] ++ [ (x, h + 1) | x <- [1..w] ] ++ [ (w + 1, y) | y <- [1..h] ] getMasu _ _ _ [] = [] getMasu i w h (c:ps) | c == '1' = masu : getMasu (i + 1) w h ps | otherwise = getMasu (i + 1) w h ps where (d, m) = divMod i w masu = (m + 1, d + 1) main = do [h, w] <- map read . words <$> getLine :: IO [Int] ps <- foldr (++) [] <$> replicateM h getLine :: IO String print $ head $ sort $ solve (getWaku w h) (getMasu 0 w h ps)