#include <bits/stdc++.h>
using namespace std;
typedef priority_queue<long long, vector<long long>> decendingQueue;
typedef priority_queue<long long, vector<long long>, greater<long long>>
    ascendingQueue;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
const int INF = 1e8;
struct point {
  int x, y;
};
void solve(long long H, long long W, long long K, std::vector<std::string> A) {
  vector<vector<long long>> dp(H, vector<long long>(W, -1));
  queue<point> q;
  for (int(i) = (0); (i) < (H); ++(i)) {
    for (int(j) = (0); (j) < (W); ++(j)) {
      if (A[i][j] == 'S') {
        q.push((point){i, j});
      }
    }
  }
  vector<point> next;
  int cnt = 1;
  while (!q.empty()) {
    point p = q.front();
    q.pop();
    if (A[p.x][p.y] == '#') {
      continue;
    }
    if (dp[p.x][p.y] == -1) {
      next.push_back(p);
      dp[p.x][p.y] = cnt;
      for (int(k) = (0); (k) < (4); ++(k)) {
        int nx = p.x + dx[k];
        int ny = p.y + dy[k];
        if (nx >= 0 && nx < H && ny >= 0 && ny < W) {
          q.push((point){nx, ny});
        }
      }
    }
  }
  while (!next.empty()) {
    cnt++;
    queue<pair<point, int>> qq;
    for (auto p : next) {
      qq.push(make_pair(p, K));
    }
    vector<point> tmpNext;
    while (!qq.empty()) {
      auto p = qq.front().first;
      auto r = qq.front().second;
      qq.pop();
      if (r < 0) {
        continue;
      }
      if (dp[p.x][p.y] != -1 && dp[p.x][p.y] != cnt - 1) {
        continue;
      }
      if (dp[p.x][p.y] == -1) {
        tmpNext.push_back((point){p.x, p.y});
        dp[p.x][p.y] = cnt;
      }
      for (int(k) = (0); (k) < (4); ++(k)) {
        int nx = p.x + dx[k];
        int ny = p.y + dy[k];
        if (nx >= 0 && nx < H && ny >= 0 && ny < W && dp[nx][ny] == -1) {
          qq.push(make_pair((point){nx, ny}, r - 1));
        }
      }
    }
    next = tmpNext;
  }
  long long ans = 1e9;
  for (int(i) = (0); (i) < (H); ++(i)) {
    ans = min(ans, dp[i][0]);
    ans = min(ans, dp[i][W - 1]);
  }
  for (int(i) = (0); (i) < (W); ++(i)) {
    ans = min(ans, dp[0][i]);
    ans = min(ans, dp[H - 1][i]);
  }
  cout << ans << endl;
}
int main() {
  long long H;
  scanf("%lld", &H);
  long long W;
  scanf("%lld", &W);
  long long K;
  scanf("%lld", &K);
  vector<string> A(H);
  for (int i = 0; i < H; i++) {
    cin >> A[i];
  }
  solve(H, W, K, std::move(A));
  return 0;
}
