#include <bits/stdc++.h>
using namespace std;
using VS = vector<string>;
using VI = vector<int>;
using VVI = vector<vector<int>>;
constexpr int MAX = numeric_limits<int>::max();
constexpr int DX[4] = {1, -1, 0, 0};
constexpr int DY[4] = {0, 0, 1, -1};
vector<pair<int, int>> visit(int H, int W, const VS& field, bool wallAllowed,
                             int D, int sx, int sy, const VVI& ldist) {
  VVI dists(H, VI(W, MAX));
  deque<tuple<int, int, int>> q;
  q.push_back(make_tuple(sx, sy, 0));
  while (!q.empty()) {
    int x, y, d;
    tie(x, y, d) = q.front();
    q.pop_front();
    if (dists[y][x] <= d) continue;
    if (ldist[y][x] != MAX) continue;
    dists[y][x] = d;
    if (d == D) continue;
    for (int dir = 0; dir < 4; ++dir) {
      int dx = DX[dir];
      int dy = DY[dir];
      int nx = x + dx;
      int ny = y + dy;
      if (nx < 0 || ny < 0 || nx >= W || ny >= H) continue;
      if (dists[ny][nx] <= d + 1) continue;
      if ((field[ny][nx] == '#' && wallAllowed) || field[ny][nx] == '.') {
        q.push_back(make_tuple(nx, ny, d + 1));
      }
    }
  }
  vector<pair<int, int>> res;
  for (int y = 0; y < H; ++y)
    for (int x = 0; x < W; ++x) {
      if (dists[y][x] < MAX) res.push_back(make_pair(x, y));
    }
  return res;
}
int main() {
  int H, W, K;
  cin >> H >> W >> K;
  VS field(H);
  for (int i = 0; i < H; ++i) cin >> field[i];
  int sx, sy;
  for (int y = 0; y < H; ++y)
    for (int x = 0; x < W; ++x)
      if (field[y][x] == 'S') {
        sx = x;
        sy = y;
      }
  VVI dist(H, VI(W, MAX));
  deque<tuple<int, int, int>> q;
  {
    auto cs = visit(H, W, field, false, K, sx, sy, dist);
    for (const auto& xy : cs) {
      int x = xy.first;
      int y = xy.second;
      q.push_back(make_tuple(x, y, 1));
    }
  }
  while (!q.empty()) {
    int x, y, d;
    tie(x, y, d) = q.front();
    q.pop_front();
    if (dist[y][x] <= d) continue;
    auto cs = visit(H, W, field, true, K, x, y, dist);
    dist[y][x] = d;
    if (x == 0 || x == W - 1 || y == 0 || y == H - 1) break;
    for (const auto& xy : cs) {
      int x = xy.first;
      int y = xy.second;
      q.push_back(make_tuple(x, y, d + 1));
    }
  }
  int best = MAX;
  for (int y = 0; y < H; ++y) {
    for (int x = 0; x < W; ++x) {
      if (x == 0 || x == W - 1 || y == 0 || y == H - 1)
        best = min(best, dist[y][x]);
    }
  }
  cout << best << "\n";
  return 0;
}
