import Control.Applicative import Control.Monad main :: IO () main = do [h, w] <- f solve [h, w] <$> replicateM h getLine >>= print where f = map read <$> words <$> getLine solve :: [Int] -> [String] -> Double solve [h, w] pss = minimum $ do (rx, ry) <- rs return $ sum $ do (bx, by) <- bs return $ dist (rx, ry) (bx, by) where rs = map (\x -> (x, 0)) [1..w] ++ map (\x -> (x,h+1)) [1..w] ++ map (\y -> (0, y)) [1..h] ++ map (\y -> (w+1,y)) [1..h] bs :: [(Int, Int)] bs = do (y, s) <- zip [1..] pss (x, c) <- zip [1..] s guard $ c == '1' return (x, y) dist :: (Int, Int) -> (Int, Int) -> Double dist (x0, y0) (x1, y1) = sqrt $ (fromIntegral dx) ^ 2 + (fromIntegral dy) ^ 2 where dx = abs (x0 - x1) dy = abs (y0 - y1)