#include <bits/stdc++.h>
using namespace std;
class point {
 public:
  int zanho, zanopen, hosuu, open, kyori, x, y;
  point(int zanho, int zanopen, int hosuu, int open, int kyori, int x, int y)
      : zanho(zanho),
        zanopen(zanopen),
        hosuu(hosuu),
        open(open),
        kyori(kyori),
        x(x),
        y(y) {}
  bool operator<(const point& p) const {
    return zanho == p.zanho
               ? zanopen == p.zanopen
                     ? hosuu == p.hosuu
                           ? open == p.open ? kyori > p.kyori : open > p.open
                           : hosuu > p.hosuu
                     : zanopen < p.zanopen
               : zanho < p.zanho;
  }
};
queue<point> P;
string s[800];
int d[800][800];
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
int main() {
  int h, w, k;
  cin >> h >> w >> k;
  int sx, sy;
  for (int i = 0; i < h; i++) {
    cin >> s[i];
    for (int j = 0; j < w; j++)
      if (s[i][j] == 'S') sx = i, sy = j;
  }
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++) d[i][j] = 1e9;
  P.push(point(k, 0, 0, 0, 1, sx, sy));
  d[sx][sy] = 0;
  int ans = 1e9;
  while (!P.empty()) {
    point p = P.front();
    P.pop();
    if (p.zanho == 0) {
      p.kyori++;
      p.zanho += k;
      p.zanopen += k;
    }
    if (p.x == 0 || p.x == h - 1 || p.y == 0 || p.y == w - 1) {
      ans = min(ans, p.kyori);
      continue;
    }
    for (int r = 0; r < 4; r++) {
      int flag = 0, flagkyori = 0;
      int tx = p.x + dx[r], ty = p.y + dy[r];
      if (d[tx][ty] < p.kyori) continue;
      if (s[tx][ty] == '#') {
        flag = 1;
        if (p.zanopen == 0) {
          flagkyori = 1;
        }
      }
      if (d[tx][ty] > p.kyori) d[tx][ty] = p.kyori + flagkyori;
      P.push(point(p.zanho - 1 + k * flagkyori,
                   p.zanopen - flag + k * flagkyori, p.hosuu + 1, p.open + flag,
                   p.kyori + flagkyori, tx, ty));
    }
  }
  cout << ans << endl;
}
