#include <bits/stdc++.h>
using namespace std;
struct cell {
  int x, y;
  cell(int x = 0, int y = 0) : x(x), y(y) {}
};
int H, W, K, d[810][810], sz;
char a[810][810];
cell q[1000000];
int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, -1, 1};
void dfs(int x, int y, int dist, int cnt, int mx, int val) {
  int k, nx, ny;
  if (dist == K) return;
  for (k = 0; k < 4; k++) {
    nx = x + dx[k], ny = y + dy[k];
    if (nx < 1 || nx > H || ny < 1 || ny > W) continue;
    if (d[nx][ny] > val + 1 && !(a[nx][ny] == '#' && cnt == mx)) {
      d[nx][ny] = val + 1;
      q[++sz] = cell(nx, ny);
      dfs(nx, ny, dist + 1, cnt + (a[nx][ny] == '#'), mx, val);
    }
  }
}
int main() {
  cin >> H >> W >> K;
  int i, j, sx, sy;
  for (i = 1; i <= H; i++)
    for (j = 1; j <= W; j++) {
      cin >> a[i][j];
      d[i][j] = (1 << 28);
      if (a[i][j] == 'S') sx = i, sy = j, d[i][j] = 0;
    }
  dfs(sx, sy, 0, 0, 0, 0);
  dfs(sx, sy, 0, 0, K, 1);
  for (i = 1; i <= sz; i++) dfs(q[i].x, q[i].y, 0, 0, K, d[q[i].x][q[i].y]);
  int res = (1 << 30);
  for (i = 1; i <= W; i++) res = min({res, d[1][i], d[H][i]});
  for (i = 1; i <= H; i++) res = min({res, d[i][1], d[i][W]});
  cout << res << "\n";
  return 0;
}
