#include <bits/stdc++.h>

using namespace std;

const int INF = 1e7;

struct dist {
  int d;
  int k;
  dist(int a, int b) : d(a), k(b) {}
  dist() : dist(0, 0) {}
  bool operator<(const dist& rhs) const {
    return d != rhs.d ? d < rhs.d : k < rhs.k;
  }
  bool operator>(const dist& rhs) const {
    return rhs < *this;
  }
  bool operator>=(const dist& rhs) const {
    return !(*this < rhs);
  }
};

struct node {
  int r;
  int c;
  dist D;
  node(int x, int y, int z, int w) : r(x), c(y), D(z, w) {}
  node() : node(0, 0, 0, 0) {}
  bool operator<(const node& rhs) const {
    return D < rhs.D;
  }
  bool operator>(const node& rhs) const {
    return rhs < *this;
  }
};

int solve()
{
  int H, W, K;
  cin >> H >> W >> K;
  vector<vector<dist>> di(H, vector<dist>(W, dist(INF, INF)));
  vector<vector<bool>> ch(H, vector<bool>(W, true));
  vector<vector<bool>> hh(H, vector<bool>(W, false));
  priority_queue<node, vector<node>, greater<>> now, nex;
  queue<pair<int,int>> hq;
  int sr, sc;
  for (int i = 0; i < H; i++) {
    string s;
    cin >> s;
    for (int j = 0; j < W; j++) {
      if (s[j] == '#') ch[i][j] = false;
      if (s[j] == 'S') sr = i, sc = j;
    }
  }
  now.emplace(sr, sc, 0, 0);
  int cnt = 1;
  while (now.size()) {
    auto n = now.top();
    now.pop();
    int r = n.r;
    int c = n.c;
    dist D = n.D;
    if (D >= di[r][c]) continue;
    di[r][c] = D;
    if (r == 0 || r == H-1 || c == 0 || c == W-1) return cnt;
    int dr[] = {0, 1, 0, -1};
    int dc[] = {1, 0, -1, 0};
    for (int i = 0; i < 4; i++) {
      int nr = r + dr[i];
      int nc = c + dc[i];
      if (hh[nr][nc]) continue;
      dist DD = D;
      DD.d++;
      if (!ch[nr][nc]) DD.k++;
      if (di[nr][nc] > DD) {
        hq.emplace(nr, nc);
        if (DD.k > (cnt - 1) * K || DD.d > cnt * K) {
          nex.emplace(nr, nc, DD.d, DD.k);
        } else {
          now.emplace(nr, nc, DD.d, DD.k);
        }
      }
    }
    if (now.size() == 0) {
      cnt++;
      swap(now, nex);
      while (hq.size()) {
        auto t = hq.front();
        hh[t.first][t.second] = true;
        hq.pop();
      }
    }
  }
  return 0;
}

int main()
{
  cout << solve() << endl;
}
