{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}

import Debug.Trace
import Data.Maybe
import qualified Data.Set as S
import qualified Data.List as L
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as B

type Index = Int
type StartPoints = S.Set (Index, Index)
type Board = (M.IntMap B.ByteString)

d = [(-1, 0), (1, 0), (0, -1), (0, 1)]

listStart' b k (y,x) l h w
  | k == 0 = l'
  | otherwise = L.foldl' step l' d
  where
    l' = S.insert (y,x) l
    ng y x = y < 0 || y >= h || x < 0 || x >= w
    visited y x = S.member (y,x) l'
    step z (dy, dx) =
      let
        y' = y + dy
        x' = x + dx
      in
        if ng y' x' || visited y' x' || v b y' x' /= '.'
        then z
        else listStart' b (k-1) (y',x') z h w

listStart :: Board -> Int -> Int -> Int -> StartPoints
listStart b k = listStart' b k s init
  where
    s = find b 'S'
    init = S.fromList []

solve :: [B.ByteString] -> Int
solve (xs:xss) = 1 + ceiling (fromIntegral m / fromIntegral k)
  where
    [h,w,k] = map readInt $ B.words xs
    b = M.fromList $ zip [0..] xss
    s = listStart b k h w
    m = S.foldl' (\z (y,x) -> min z (minimum [y, x, h-y-1, w-x-1])) 1000000000 s

readInt = fst . fromJust . B.readInt
main = B.getContents >>= print . solve .  B.lines

--------------------------------------------------
-- Matrix
--------------------------------------------------
class (Show a) => Matrix a b | a -> b where
   v :: a -> Int -> Int -> b
   find :: a -> b -> (Int,Int)
   update :: a -> Int -> Int -> b -> a
   initMat :: Int -> Int -> b -> a

instance Matrix Board Char where
  v b i = B.index (b M.! i)
  find b c = head tmp3
    where
      tmp = M.map (B.elemIndex c) b
      tmp2 = M.filterWithKey (\i x -> isJust x) tmp
      tmp3 = map (\(i, x) -> (i, fromJust x)) (M.toList tmp2)
  update b i j c = M.update (Just . replace) i b
    where
      replace x = B.append (B.take j x) $ B.cons c (B.drop (j+1) x)
