#include <bits/stdc++.h>
using namespace std;
int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
int H, W, K;
string A[810];
int main() {
  cin >> H >> W >> K;
  int startX, startY;
  for (int i = 0; i < H; i++) {
    cin >> A[i];
    for (int j = 0; j < W; j++) {
      if (A[i][j] == 'S') {
        startY = i;
        startX = j;
      }
    }
  }
  bool visit[810][810];
  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++) visit[i][j] = false;
  int steps[805][805];
  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++) steps[i][j] = -1;
  queue<pair<pair<int, int>, pair<int, pair<int, int> > > > q;
  pair<pair<int, int>, pair<int, pair<int, int> > > tmp =
      make_pair(make_pair(startY, startX), make_pair(1, make_pair(0, 0)));
  q.push(tmp);
  visit[startY][startX] = true;
  while (!q.empty()) {
    pair<int, int> nowPos = q.front().first;
    int nowStep = q.front().second.first;
    pair<int, int> nowState = q.front().second.second;
    q.pop();
    for (int k = 0; k < 4; k++) {
      int nextY = nowPos.first + dy[k], nextX = nowPos.second + dx[k];
      if (!(0 <= nextY && nextY < H) || !(0 <= nextX && nextX < W)) continue;
      if (steps[nextY][nextX] != -1 && steps[nextY][nextX] <= nowStep) continue;
      if (A[nextY][nextX] == '#') {
        int tmpStep = nowStep;
        if (nowStep == 1) tmpStep++;
        if (nowState.second < K) {
          tmp = make_pair(make_pair(nextY, nextX),
                          make_pair(tmpStep, make_pair(nowState.first,
                                                       nowState.second + 1)));
          steps[nextY][nextX] = tmpStep;
        } else {
          tmp = make_pair(make_pair(nextY, nextX),
                          make_pair(tmpStep + 1, make_pair(0, 1)));
          steps[nextY][nextX] = tmpStep + 1;
        }
      }
      if (A[nextY][nextX] == '.') {
        if (nowState.first < K) {
          tmp = make_pair(make_pair(nextY, nextX),
                          make_pair(nowStep, make_pair(nowState.first + 1,
                                                       nowState.second)));
          steps[nextY][nextX] = nowStep;
        } else {
          tmp = make_pair(make_pair(nextY, nextX),
                          make_pair(nowStep + 1, make_pair(1, 0)));
          steps[nextY][nextX] = nowStep + 1;
        }
      }
      visit[nextY][nextX] = true;
      q.push(tmp);
    }
  }
  int ans = 1e9;
  for (int i = 0; i < H; i++)
    for (int j = 0; j < W; j++)
      if (i == 0 || i == H - 1 || j == 0 || j == W - 1)
        ans = min(ans, steps[i][j]);
  cout << ans << endl;
  return 0;
}
