#include <bits/stdc++.h>
using namespace std;
const int N = 808;
char c[N][N];
pair<int, int> dp[N][N];
int ans = 1e9;
int h, w, K;
bool YO = 1;
queue<tuple<int, int, int, int, int>> q;
void haha(int i, int j, int rnd, bool first, int k) {
  if (c[i][j] == 'S' && !YO) return;
  YO = 0;
  if (dp[i][j].first < rnd) return;
  if (dp[i][j].first == rnd && dp[i][j].second <= k) return;
  dp[i][j] = make_pair(rnd, k);
  if (i == 0 || i == h - 1) {
    ans = min(ans, rnd);
    return;
  }
  if (j == 0 || j == w - 1) {
    ans = min(ans, rnd);
    return;
  }
  k--;
  if (k == 0) {
    first ^= 1;
    k = K;
    rnd++;
  }
  int rndp, firstp, kp;
  rndp = rnd;
  firstp = first;
  kp = k;
  if (c[i - 1][j] == '#' && firstp == 1) {
    firstp ^= 1;
    rndp++;
    kp = K;
  }
  if (c[i - 1][j] == '.' && firstp == 0) {
    firstp ^= 1;
    rndp++;
    kp = K;
  }
  q.push(make_tuple(i - 1, j, rndp, firstp, kp));
  rndp = rnd;
  firstp = first;
  kp = k;
  if (c[i + 1][j] == '#' && firstp == 1) {
    firstp ^= 1;
    rndp++;
    kp = K;
  }
  if (c[i + 1][j] == '.' && firstp == 0) {
    firstp ^= 1;
    rndp++;
    kp = K;
  }
  q.push(make_tuple(i + 1, j, rndp, firstp, kp));
  rndp = rnd;
  firstp = first;
  kp = k;
  if (c[i][j - 1] == '#' && firstp == 1) {
    firstp ^= 1;
    rndp++;
    kp = K;
  }
  if (c[i][j - 1] == '.' && firstp == 0) {
    firstp ^= 1;
    rndp++;
    kp = K;
  }
  q.push(make_tuple(i, j - 1, rndp, firstp, kp));
  rndp = rnd;
  firstp = first;
  kp = k;
  if (c[i][j + 1] == '#' && firstp == 1) {
    firstp ^= 1;
    rndp++;
    kp = K;
  }
  if (c[i][j + 1] == '.' && firstp == 0) {
    firstp ^= 1;
    rndp++;
    kp = K;
  }
  q.push(make_tuple(i, j + 1, rndp, firstp, kp));
  return;
}
int main() {
  cin >> h >> w >> K;
  int starti, startj;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      cin >> c[i][j];
      if (c[i][j] == 'S') {
        starti = i;
        startj = j;
      }
      dp[i][j] = make_pair(1e9, 1e9);
    }
  }
  q.push(make_tuple(starti, startj, 1, 1, K));
  while (!q.empty()) {
    tuple<int, int, int, int, int> t = q.front();
    q.pop();
    haha(get<0>(t), get<1>(t), get<2>(t), get<3>(t), get<4>(t));
  }
  cout << ans;
  return 0;
}
