#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using Pll = pair<ll, ll>;
using Pii = pair<int, int>;
constexpr int H_MAX = 800;
constexpr int W_MAX = 800;
constexpr int dyx[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
int H, W, K;
Pii start = {-1, -1};
vector<string> a(H_MAX);
vector<vector<int>> shortest_turn(H_MAX, vector<int>(W_MAX, 1 << 30));
inline int calc_shortest_turn() {
  priority_queue<pair<int, Pii>, vector<pair<int, Pii>>,
                 greater<pair<int, Pii>>>
      que;
  que.emplace(0, start);
  shortest_turn[start.first][start.second] = 0;
  int turn;
  Pii p;
  while (!que.empty()) {
    tie(turn, p) = que.top();
    que.pop();
    if (shortest_turn[p.first][p.second] < turn) continue;
    if (p.first == 0 || p.first == H - 1 || p.second == 0 ||
        p.second == W - 1) {
      return turn;
    }
    for (int k = 0; k < 4; ++k) {
      Pii q = {p.first + dyx[k][0], p.second + dyx[k][1]};
      if (q.first < 0 || H <= q.first || q.second < 0 || W <= q.second)
        continue;
      int new_turn = turn + 1;
      if (a[p.first][p.second] != '#' && a[q.first][q.second] == '#') {
        new_turn = max(new_turn, turn / K * K + K + 1);
      }
      if (shortest_turn[q.first][q.second] > new_turn) {
        shortest_turn[q.first][q.second] = new_turn;
        que.emplace(new_turn, Pii(q.first, q.second));
      }
    }
  }
  return -1;
}
int main() {
  std::ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> H >> W >> K;
  for (int i = 0; i < H; ++i) {
    cin >> a[i];
    for (int j = 0; j < W; ++j) {
      if (a[i][j] != '#') {
        if (a[i][j] == 'S') {
          start = {i, j};
          shortest_turn[i][j] = 0;
        }
      }
    }
  }
  cout << (calc_shortest_turn() + K - 1) / K << endl;
}
