#include <bits/stdc++.h>
using namespace std;
const long X[4] = {1, -1, 0, 0}, Y[4] = {0, 0, 1, -1};
long b[801][801];
char a[801][801];
void findx(long x, long y, long s) {
  long k;
  if (a[x][y] == '#') {
    k = 2;
  } else if (a[x][y] == '.') {
    k = 1;
  } else if (a[x][y] == 'S') {
    k = 0;
  }
  if (b[x][y] > s + k) {
    b[x][y] = s + k;
    for (long i = 0; i < 4; i++) {
      if (x + X[i] >= 0 && x + X[i] <= 800 && y + Y[i] >= 0 &&
          y + Y[i] <= 800 && a[x + X[i]][y + Y[i]] != 0)
        findx(x + X[i], y + Y[i], s + k);
      ;
    }
  }
}
int main() {
  long W, H, K, x, y, n;
  memset(a, 0, sizeof(a));
  for (long i = 0; i <= 800; i++)
    for (long j = 0; j <= 800; j++) b[i][j] = pow(2, 30) - 1 + pow(2, 30);
  cin >> H >> W >> K;
  for (long i = 0; i < H; i++) {
    getchar();
    for (long j = 0; j < W; j++) {
      scanf("%c", &a[i][j]);
      if (a[i][j] == 'S') {
        x = i;
        y = j;
      }
    }
  }
  findx(x, y, 0);
  n = K;
  for (long i = 0; i < H; i++) {
    if (b[i][W - 1] < n) n = b[i][W - 1];
    if (b[i][0] < n) n = b[i][0];
  }
  for (long j = 0; j < W; j++) {
    if (b[H - 1][j] < n) n = b[H - 1][j];
    if (b[0][j] < n) n = b[0][j];
  }
  cout << n;
  return 0;
}
