#include <bits/stdc++.h>
using namespace std;
int main() {
  constexpr int64_t INF = 1e9;
  int64_t H, W, K;
  cin >> H >> W >> K;
  vector<string> grid(H);
  for (int i = 0; i < H; ++i) {
    cin >> grid[i];
  }
  int dx[4] = {0, 0, 1, -1};
  int dy[4] = {1, -1, 0, 0};
  auto in = [&](int x, int y) -> bool {
    return x >= 0 && x < W && y >= 0 && y < H;
  };
  int Sx = 0, Sy = 0;
  for (int i = 0; i < H; ++i) {
    for (int j = 0; j < W; ++j) {
      if (grid[i][j] == 'S') {
        Sx = j, Sy = i;
      }
    }
  }
  vector<vector<int64_t>> distS(H, vector<int64_t>(W, INF));
  distS[Sy][Sx] = 0;
  {
    deque<pair<int, int>> que;
    que.emplace_back(Sy, Sx);
    while (!que.empty()) {
      auto p = que.front();
      que.pop_front();
      int x = p.second, y = p.first;
      for (int k = 0; k < 4; ++k) {
        int nx = x + dx[k];
        int ny = y + dy[k];
        if (!in(nx, ny) || grid[ny][nx] == '#' ||
            distS[ny][nx] <= distS[y][x] + 1) {
          continue;
        }
        distS[ny][nx] = distS[y][x] + 1;
        que.emplace_back(ny, nx);
      }
    }
  }
  auto check = [&](int64_t mid) -> bool {
    vector<vector<int64_t>> esc(H, vector<int64_t>(W, INF));
    for (int i = 0; i < H; ++i) {
      for (int j = 0; j < W; ++j) {
        if (i != 0 && i != H - 1 && j != 0 && j != W - 1) {
          continue;
        }
        vector<vector<int64_t>> cost(H, vector<int64_t>(W, INF));
        cost[i][j] = (grid[i][j] == '#');
        vector<vector<int64_t>> dist(H, vector<int64_t>(W, INF));
        dist[i][j] = 0;
        deque<pair<int, int>> que;
        que.emplace_back(i, j);
        while (!que.empty()) {
          auto p = que.front();
          que.pop_front();
          int x = p.second, y = p.first;
          for (int k = 0; k < 4; ++k) {
            int nx = x + dx[k];
            int ny = y + dy[k];
            if (!in(nx, ny)) {
              continue;
            }
            int add = (grid[ny][nx] == '#');
            if (cost[y][x] + add > K * (mid - 1) ||
                dist[ny][nx] <= dist[y][x] + 1) {
              continue;
            }
            dist[ny][nx] = dist[y][x] + 1;
            cost[ny][nx] = cost[y][x] + add;
            que.emplace_back(ny, nx);
          }
        }
        for (int h = 0; h < H; ++h) {
          for (int w = 0; w < W; ++w) {
            esc[h][w] = min(esc[h][w], dist[h][w]);
          }
        }
      }
    }
    for (int i = 0; i < H; ++i) {
      for (int j = 0; j < W; ++j) {
        if (distS[i][j] + esc[i][j] <= K * mid) {
          return true;
        }
      }
    }
    return false;
  };
  int64_t low = -1, high = INF;
  while (high - low > 1) {
    int64_t mid = (high + low) / 2;
    (check(mid) ? high : low) = mid;
  }
  cout << high << "\n";
  return 0;
}
