#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 7;
const long long mod = 1e9 + 7;
const long long big = 1e18;
const double PI = 2 * asin(1);
int main() {
  int H, W, K;
  cin >> H >> W >> K;
  vector<string> A(H);
  for (int i = 0; i < H; ++i) cin >> A[i];
  int sx, sy;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      if (A[i][j] == 'S') {
        sx = i;
        sy = j;
      }
    }
  }
  queue<pair<int, int> > que;
  queue<int> numque;
  que.push(make_pair(sx, sy));
  numque.push(0);
  map<pair<int, int>, int> amap;
  pair<int, int> state;
  int x, y, num;
  while (!que.empty()) {
    state = que.front();
    que.pop();
    num = numque.front();
    numque.pop();
    x = state.first;
    y = state.second;
    if (num > K) break;
    A[x][y] = '1';
    if (amap[make_pair(x - 1, y)] == 0 && x - 1 >= 0 && A[x - 1][y] == '.') {
      que.push(make_pair(x - 1, y));
      numque.push(num + 1);
    }
    if (amap[make_pair(x + 1, y)] == 0 && x + 1 < H && A[x + 1][y] == '.') {
      que.push(make_pair(x + 1, y));
      numque.push(num + 1);
    }
    if (amap[make_pair(x, y - 1)] == 0 && y - 1 >= 0 && A[x][y - 1] == '.') {
      que.push(make_pair(x, y - 1));
      numque.push(num + 1);
    }
    if (amap[make_pair(x, y + 1)] == 0 && y + 1 < W && A[x][y + 1] == '.') {
      que.push(make_pair(x, y + 1));
      numque.push(num + 1);
    }
  }
  int ans = inf;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      if (A[i][j] == '#' || A[i][j] == '.') continue;
      if (i % K == 0) {
        ans = min(ans, A[i][j] - '0' + i / K);
      } else {
        ans = min(ans, A[i][j] - '0' + i / K + 1);
      }
      if ((H - i - 1) % K == 0) {
        ans = min(ans, A[i][j] - '0' + (H - i - 1) / K);
      } else {
        ans = min(ans, A[i][j] - '0' + (H - i - 1) / K + 1);
      }
      if (j % K == 0) {
        ans = min(ans, A[i][j] - '0' + j / K);
      } else {
        ans = min(ans, A[i][j] - '0' + j / K + 1);
      }
      if ((W - j - 1) % K == 0) {
        ans = min(ans, A[i][j] - '0' + (W - j - 1) / K);
      } else {
        ans = min(ans, A[i][j] - '0' + (W - j - 1) / K + 1);
      }
    }
  }
  cout << ans << endl;
}
