#include <bits/stdc++.h>
using namespace std;
char c[805][805];
const int INF = 2e9 + 3;
int n, m, k;
int sx, sy;
int a[805][805];
int d[805][805];
int f[805][805];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int main() {
  cin >> n >> m >> k;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> c[i][j];
      if (c[i][j] == 'S') sx = i, sy = j;
    }
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) a[i][j] = INF, d[i][j] = INF;
  queue<pair<int, int> > que;
  que.push(make_pair(sx, sy));
  a[sx][sy] = 0;
  d[sx][sy] = k;
  while (que.size()) {
    int x = que.front().first;
    int y = que.front().second;
    que.pop();
    for (int i = 0; i < 4; i++) {
      int nx = x + dx[i];
      int ny = y + dy[i];
      if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
      if (c[nx][ny] != '#') {
        int p = a[x][y];
        if (!d[x][y]) {
          p++;
          if (p < a[nx][ny] || (p == a[nx][ny] && d[x][y] - 1 > d[nx][ny])) {
            a[nx][ny] = p;
            d[nx][ny] = k;
            f[nx][ny] = k;
            que.push(make_pair(nx, ny));
          }
        } else {
          if (p < a[nx][ny] || (p == a[nx][ny] && d[x][y] - 1 > d[nx][ny])) {
            a[nx][ny] = p;
            d[nx][ny] = d[x][y] - 1;
            que.push(make_pair(nx, ny));
          }
        }
      } else {
        int p = a[x][y], q = f[x][y];
        if (!d[x][y]) {
          p++;
          if (p < a[nx][ny] || (p == a[nx][ny] && d[x][y] - 1 > d[nx][ny])) {
            a[nx][ny] = p;
            d[nx][ny] = k;
            f[nx][ny] = f[x][y] + k - 1;
            que.push(make_pair(nx, ny));
          }
        } else {
          int q = f[x][y];
          if (!q) {
            p++;
            if (p < a[nx][ny] || (p == a[nx][ny] && d[x][y] - 1 > d[nx][ny])) {
              a[nx][ny] = p;
              d[nx][ny] = k;
              f[nx][ny] = k - 1;
              que.push(make_pair(nx, ny));
            }
          } else {
            if (p < a[nx][ny] || (p == a[nx][ny] && d[x][y] - 1 > d[nx][ny]) ||
                (p == a[nx][ny] && d[x][y] - 1 == d[nx][ny] &&
                 f[x][y] - 1 > f[nx][ny])) {
              a[nx][ny] = p;
              d[nx][ny] = d[x][y] - 1;
              f[nx][ny] = f[x][y] - 1;
              que.push(make_pair(nx, ny));
            }
          }
        }
      }
    }
  }
  int ans = INF;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (i == 0 || i == n - 1 || j == 0 || j == m - 1) ans = min(a[i][j], ans);
  cout << ans + 1;
  return 0;
}
