#include <bits/stdc++.h>
using namespace std;
const int MAX = 30000;
int memo[1024][1024];
int H, W, K;
queue<pair<int, int> > q;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
bool check(int x, int y) { return 0 <= x && x < W && 0 <= y && y < H; }
int main(void) {
  string str[1024];
  cin >> H >> W >> K;
  for (int i = 0; i < (H); ++i) cin >> str[i];
  for (int i = 0; i < (1024); ++i)
    for (int j = 0; j < (1024); ++j) memo[i][j] = 100000000;
  for (int i = 0; i < (H); ++i)
    for (int j = 0; j < (W); ++j)
      if (str[i][j] == 'S') {
        q.push(make_pair(j, i));
        q.push(make_pair(j, i));
        str[i][j] = '.';
        i = H;
        j = W;
      }
  int mc = 0;
  for (int xyz = 0; xyz < (1); ++xyz) {
    queue<pair<int, int> > mv;
    mc++;
    int ss = q.size();
    for (int stu = 0; stu < (1); ++stu) {
      mv.push(q.front());
      q.pop();
      for (int i = 0; i < (K); ++i) {
        int si = mv.size();
        for (int j = 0; j < (si); ++j) {
          pair<int, int> pos = mv.front();
          mv.pop();
          if (memo[pos.second][pos.first] <= mc) continue;
          memo[pos.second][pos.first] = mc;
          for (int k = 0; k < (4); ++k) {
            int nx = pos.first + dx[k];
            int ny = pos.second + dy[k];
            if (!check(nx, ny)) continue;
            if (memo[ny][nx] <= mc) continue;
            if (str[ny][nx] == '#') continue;
            if (nx == 0 || ny == 0 || nx == W - 1 || ny == H - 1) {
              cout << mc << endl;
              return 0;
            }
            mv.push(make_pair(nx, ny));
            q.push(make_pair(nx, ny));
          }
        }
      }
    }
  }
  int ans = 1000000000;
  while (!q.empty()) {
    pair<int, int> t = q.front();
    q.pop();
    ans = min(ans, t.first / K + t.first % K + 1);
    ans = min(ans, (W - 1 - t.first) / K + (W - 1 - t.first) % K + 1);
    ans = min(ans, t.second / K + t.second % K + 1);
    ans = min(ans, (H - 1 - t.second) / K + (H - 1 - t.second) % K + 1);
  }
  cout << ans << endl;
  return 0;
}
