#include <bits/stdc++.h>
using namespace std;
template <class T>
inline T re() {
  T N = 0;
  char c = getchar();
  bool neg = 0;
  for (; c < '0' || c > '9'; c = getchar()) neg |= c == '-';
  for (; c >= '0' && c <= '9'; c = getchar()) N = (N << 3) + (N << 1) + c - '0';
  return neg ? -N : N;
}
int h, w, k;
inline bool ins(int r, int c) { return 1 <= r && r <= h && 1 <= c && c <= w; }
char g[805][805];
pair<int, int> d[805][805];
struct dt {
  int r, c, dm, dk;
  dt(int r = 0, int c = 0, int dm = 0, int dk = 0)
      : r(r), c(c), dm(dm), dk(dk) {}
  bool operator<(const dt &rhs) const {
    return dm == rhs.dm ? dk > rhs.dk : dm > rhs.dm;
  }
};
priority_queue<dt> q;
int dr[] = {1, 0, -1, 0};
int dc[] = {0, 1, 0, -1};
void dijk(pair<int, int> st) {
  q.emplace(st.first, st.second, 0, k);
  memset(d, 0x3f3f3f3f, sizeof(d));
  d[st.first][st.second] = {0, k};
  while (!q.empty()) {
    dt u = q.top();
    q.pop();
    pair<int, int> D = make_pair(u.dm, u.dk);
    if (D < d[u.r][u.c]) continue;
    for (int i = 0; i < 4; i++) {
      pair<int, int> x = {u.r + dr[i], u.c + dc[i]};
      if (!ins(x.first, x.second)) continue;
      int dm, dk;
      if (g[x.first][x.second] == g[u.r][u.c]) {
        dk = u.dk + 1;
        dm = u.dm;
        if (dk == k + 1) dm++, dk = 0;
      } else if (g[x.first][x.second] == '#') {
        dm = u.dm, dk = 1;
      } else {
        dm = u.dm + 1;
        dk = 1;
      }
      if (make_pair(dm, dk) < d[x.first][x.second]) {
        d[x.first][x.second] = {dm, dk};
        q.emplace(x.first, x.second, dm, dk);
      }
    }
  }
}
int main() {
  scanf("%d %d %d", &h, &w, &k);
  pair<int, int> st = {-1, -1};
  for (int i = 1; i <= h; i++) {
    scanf("%s", g[i] + 1);
    for (int j = 1; j <= w; j++)
      if (g[i][j] == 'S') {
        st = {i, j};
        g[i][j] = '.';
      }
  }
  dijk(st);
  int mn = 0x3f3f3f3f;
  for (int i = 1; i <= h; i++) {
    mn = min(mn, d[i][1].first + (g[i][1] == '#'));
    mn = min(mn, d[i][w].first + (g[i][w] == '#'));
  }
  for (int i = 1; i <= w; i++) {
    mn = min(mn, d[1][i].first + (g[1][i] == '#'));
    mn = min(mn, d[h][i].first + (g[h][i] == '#'));
  }
  cout << mn << '\n';
  return 0;
}
