#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const int dh[] = {1, -1, 0, 0};
const int dw[] = {0, 0, 1, -1};
struct State {
  int h;
  int w;
  int rest;
  int masic;
  State(int h, int w, int rest, int masic)
      : h(h), w(h), rest(rest), masic(masic) {}
  bool operator>(const State& s) const {
    if (masic != s.masic) return masic > s.masic;
    return rest < s.rest;
  }
};
int H, W, K;
vector<string> a;
vector<vector<int> > memo, memo2;
int ans;
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cin >> H >> W >> K;
  a.resize(H);
  for (int i = 0; i < H; i++) {
    cin >> a[i];
  }
  int ch = -1, cw;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (a[i][j] == 'S') {
        ch = i;
        cw = j;
        a[i][j] = '.';
        if (i == 0 || i == H - 1 || j == 0 || j == W - 1) {
          cout << 0 << endl;
          return 0;
        }
        break;
      }
    }
    if (ch != -1) break;
  }
  memo.resize(H, vector<int>(W, INF));
  queue<pair<int, int> > q;
  memo[ch][cw] = 0;
  q.push(pair<int, int>(ch, cw));
  while (!q.empty()) {
    int h, w;
    tie(h, w) = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      int nh = h + dh[i], nw = w + dw[i];
      if (nh < 0 || nh >= H || nw < 0 || nw >= W) continue;
      if (a[nh][nw] == '#') continue;
      if (memo[nh][nw] != INF) continue;
      memo[nh][nw] = memo[h][w] + 1;
      q.push(pair<int, int>(nh, nw));
    }
  }
  ans = INF;
  priority_queue<State, vector<State>, greater<State> > pq;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (memo[i][j] == INF) continue;
      int ma;
      if (memo[i][j] == 0)
        ma = 0;
      else
        ma = (memo[i][j] - 1) / K;
      if (i == 0 || j == 0 || i == H - 1 || j == W - 1) {
        ans = min(ans, ma + 1);
      } else {
        pq.push(State(i, j, K, ma + 1));
      }
      memo[i][j] = INF;
    }
  }
  memo2.resize(H, vector<int>(W, -1));
  while (!pq.empty()) {
    State s = pq.top();
    pq.pop();
    if (memo[s.h][s.w] < s.masic) continue;
    if (memo[s.h][s.w] == s.masic && memo2[s.h][s.w] >= s.rest) continue;
    memo[s.h][s.w] = s.masic;
    memo2[s.h][s.w] = s.rest;
    if (s.h == 0 || s.w == 0 || s.h == H - 1 || s.w == W - 1) {
      ans = min(ans, s.masic + 1);
      continue;
    }
    for (int i = 0; i < 4; i++) {
      int nh = s.h + dh[i], nw = s.w + dw[i];
      if (nh < 0 || nh >= H || nw < 0 || nw >= W) continue;
      int nr = s.rest, nm = s.masic;
      if (s.rest == 0) {
        nr = K + 1;
        nm++;
      }
      nr--;
      if (memo[nh][nw] < nm) continue;
      if (memo[nh][nw] == nm && memo2[nh][nw] >= nr) continue;
      pq.push(State(nh, nw, nr, nm));
    }
  }
  cout << ans << endl;
  return 0;
}
