import queues, strutils, sequtils

let
  tmp = stdin.readline.split.map(parseInt)
  (H, W, K) = (tmp[0], tmp[1], tmp[2])
var
  A = newSeq[string](H)
  board = newSeqWith(H, newSeqWith(W, false))
  sr, sc: int
for i in 0..<H:
  A[i] = stdin.readline
  for j in 0..<W:
    if A[i][j] == 'S':
      (sr, sc) = (i, j)

let drc = [(-1, 0), (0, 1), (1, 0), (0, -1)]
proc in_board(r, c: int): bool =
  return 0 <= r and r < H and 0 <= c and c < W
var
  que = initQueue[(int, int, int)]()
  init_sq = newSeq[(int, int)]()
que.add((sr, sc, 0))

while que.len > 0:
  let
    p = que.pop
    (r, c, k) = p
  if board[r][c]:
    continue
  if r == 0 or c == 0 or r == H - 1 or c == W - 1:
    echo(1)
    quit()
  board[r][c] = true
  init_sq.add((r, c))
  for d in drc:
    let
      (dr, dc) = d
      (nr, nc) = (r + dr, c + dc)
    if k <= K and in_board(nr, nc) and A[nr][nc] != '#' and not board[nr][nc]:
      que.add((nr, nc, k + 1))

var ans = 1
while true:
  var flag = false
  while init_sq.len > 0:
    let (r, c) = init_sq.pop
    que.add((r, c, 1))
  while que.len > 0:
    let
      p = que.pop
      (r, c, k) = p
    if r == 0 or c == 0 or r == H - 1 or c == W - 1:
      flag = true
      break
    board[r][c] = true
    init_sq.add((r, c))
    for d in drc:
      let
        (dr, dc) = d
        (nr, nc) = (r + dr, c + dc)
      if k <= K and in_board(nr, nc) and not board[nr][nc]:
        que.add((nr, nc, k + 1))
  if flag:
    echo(ans + 1)
    break
  else:
    ans.inc
