#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f2f1f0f;
const int MAX_N = 8e2 + 10;
int N, M, K;
char Mp[MAX_N][MAX_N];
bool Vis[MAX_N][MAX_N];
int main() {
  cin >> N >> M >> K;
  for (int i = 0; i < N; i++) scanf("%s", Mp[i]);
  pair<int, int> st;
  for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++)
      if (Mp[i][j] == 'S') st = make_pair(i, j);
  int ans = 0;
  bool finish = false;
  vector<pair<pair<int, int>, pair<int, int>>> next;
  next.push_back(make_pair(make_pair(0, 0), st));
  while (1) {
    ans++;
    priority_queue<pair<pair<int, int>, pair<int, int>>,
                   vector<pair<pair<int, int>, pair<int, int>>>,
                   greater<pair<pair<int, int>, pair<int, int>>>>
        Q;
    for (pair<pair<int, int>, pair<int, int>> &e : next) Q.push(e);
    next.clear();
    while (!Q.empty()) {
      pair<pair<int, int>, pair<int, int>> val = Q.top();
      Q.pop();
      pair<int, int> temp[2];
      tie(temp[0], temp[1]) = val;
      int c, m, x, y;
      tie(c, m) = temp[0], tie(x, y) = temp[1];
      if (x == 0 || y == 0 || x == (N - 1) || y == (M - 1)) {
        finish = true;
        break;
      }
      if (m == (ans * K)) {
        next.push_back(val);
        continue;
      }
      if (Vis[x][y] == true) continue;
      Vis[x][y] = true;
      for (int k = 0; k < 4; k++) {
        int nx = x + "1012"[k] - '1', ny = y + "0121"[k] - '1';
        if (nx < 0 || ny < 0 || nx >= N || ny >= M) continue;
        if (Vis[nx][ny]) continue;
        pair<int, int> ns = make_pair(nx, ny),
                       nv = make_pair(c + (Mp[nx][ny] == '#'), m + 1);
        if (nv.first > ((ans - 1) * K)) {
          next.push_back(make_pair(nv, ns));
          continue;
        }
        Q.push(make_pair(nv, ns));
      }
    }
    for (pair<pair<int, int>, pair<int, int>> &e : next)
      e.first.second = ans * K;
    if (finish) break;
  }
  printf("%d\n", ans);
  return 0;
}
