#include <bits/stdc++.h>
using namespace std;
int n, m, k;
char a[805][805];
int dis[805][805], head, tail;
int dx[5] = {0, -1, 0, 1, 0}, dy[5] = {0, 0, 1, 0, -1};
bool vis[805][805];
struct Node {
  int x, y, t;
} seq[805 * 805], s;
bool Check(int x, int y) {
  if (x < 1 || x > n) return 0;
  if (y < 1 || y > m) return 0;
  if (vis[x][y]) return 0;
  return 1;
}
void Dfs(int x, int y, int t, int dep) {
  if (dep > k) return;
  vis[x][y] = 1;
  for (int i = 1; i <= 4; i++) {
    int px = x + dx[i], py = y + dy[i];
    if (Check(px, py) && a[px][py] != '#') {
      Node r;
      r.x = px;
      r.y = py;
      r.t = t + 1;
      seq[++tail] = r;
      dis[r.x][r.y] = r.t;
      Dfs(px, py, t, dep + 1);
    }
  }
}
void Dfs1(int x, int y, int t, int dep) {
  if (dep > k) return;
  vis[x][y] = 1;
  for (int i = 1; i <= 4; i++) {
    int px = x + dx[i], py = y + dy[i];
    if (Check(px, py)) {
      Node r;
      r.x = px;
      r.y = py;
      r.t = t + 1;
      seq[++tail] = r;
      dis[r.x][r.y] = r.t;
      Dfs1(px, py, t, dep + 1);
    }
  }
}
void Bfs(Node s) {
  memset(dis, 60, sizeof(dis));
  memset(vis, 0, sizeof(vis));
  dis[s.x][s.y] = 1;
  s.t = 1;
  head = 1;
  tail = 0;
  seq[++tail] = s;
  vis[s.x][s.y] = 1;
  for (int i = 1; i <= 4; i++) {
    int px = s.x + dx[i], py = s.y + dy[i];
    if (Check(px, py) && a[px][py] != '#') {
      Node r;
      r.x = px;
      r.y = py;
      r.t = s.t;
      seq[++tail] = r;
      dis[r.x][r.y] = r.t;
      Dfs(px, py, s.t - 1, 1);
    }
  }
  while (head <= tail) {
    Node now = seq[head];
    for (int i = 1; i <= 4; i++) {
      int px = now.x + dx[i], py = now.y + dy[i];
      if (Check(px, py)) {
        Node r;
        r.x = px;
        r.y = py;
        r.t = now.t + 1;
        seq[++tail] = r;
        dis[r.x][r.y] = r.t;
        Dfs1(px, py, now.t, 1);
      }
    }
    head++;
  }
}
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= n; i++) {
    getchar();
    for (int j = 1; j <= m; j++) {
      scanf("%c", &a[i][j]);
      if (a[i][j] == 'S') s.x = i, s.y = j;
    }
  }
  Bfs(s);
  int ans = 1 << 30;
  for (int i = 1; i <= n; i++) ans = min(ans, dis[i][m]);
  for (int j = 1; j <= m; j++) ans = min(ans, dis[n][j]);
  printf("%d\n", ans);
}
