#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using Graph = vector<vector<int>>;
using WGraph = vector<vector<pair<int, ll>>>;
template <class T>
inline bool chmax(T &a, const T &b) {
  if (b > a) {
    a = b;
    return true;
  }
  return false;
}
template <class T>
inline bool chmin(T &a, const T &b) {
  if (b < a) {
    a = b;
    return true;
  }
  return false;
}
constexpr int dx[4] = {-1, 0, 0, 1}, dy[4] = {0, -1, 1, 0};
constexpr int INF = 1e9;
constexpr int MOD = 1e9 + 7;
constexpr long long LINF = 1e18;
constexpr double EPS = 1e-10;
constexpr double PI = M_PI;
void solve() {
  int H, W, K;
  cin >> H >> W >> K;
  vector<string> a(H);
  for (int i = 0; i < H; ++i) cin >> a[i];
  int si = -1, sj = -1;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      if (a[i][j] == 'S') {
        si = i, sj = j;
        break;
      }
    }
    if (si != -1) break;
  }
  using T = tuple<int, int, int>;
  using P = pair<T, int>;
  vector<vector<T>> dis(H, vector<T>(W, make_tuple(INF, INF, INF)));
  dis[si][sj] = make_tuple(0, 0, 0);
  priority_queue<P, vector<P>, greater<P>> que;
  que.push(make_pair(make_tuple(0, 0, 0), si * W + sj));
  while (!que.empty()) {
    auto p = que.top();
    que.pop();
    int c = get<0>(p.first), d = get<1>(p.first), r = get<2>(p.first),
        x = p.second / W, y = p.second % W;
    if (get<0>(dis[x][y]) < c || get<1>(dis[x][y]) < d || get<2>(dis[x][y]) < r)
      continue;
    for (int i = 0; i < 4; ++i) {
      int nx = x + dx[i], ny = y + dy[i];
      if (nx < 0 || H <= nx || ny < 0 || W <= ny) continue;
      T n;
      if (r == 0) {
        if (a[nx][ny] == '#') {
          if (d < (c - 1) * K) {
            n = make_tuple(c + 1, d + 1, -K + 1);
          } else {
            n = make_tuple(c + 2, d + 1, -K + 1);
          }
        } else {
          n = make_tuple(c + 1, d, -K + 1);
        }
      } else if (a[nx][ny] == '.') {
        n = make_tuple(c, d, r + 1);
      } else {
        if (d < (c - 1) * K) {
          n = make_tuple(c, d + 1, r + 1);
        } else {
          n = make_tuple(c + 1, d + 1, -K + 1);
        }
      }
      if (n < dis[nx][ny]) {
        dis[nx][ny] = n;
        que.push(make_pair(n, nx * W + ny));
      }
    }
  }
  int res = INF;
  for (int i = 0; i < H; ++i) {
    chmin(res, get<0>(dis[i][0]));
    chmin(res, get<0>(dis[i][W - 1]));
  }
  for (int i = 0; i < W; ++i) {
    chmin(res, get<0>(dis[0][i]));
    chmin(res, get<0>(dis[H - 1][0]));
  }
  cout << res << '\n';
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout << fixed << setprecision(20);
  solve();
  return 0;
}
