#include <bits/stdc++.h>
using namespace std;
const int N = 800 + 5;
pair<int, int> d[N][N];
char a[N][N];
bool mark[N][N];
int n, m, k;
int xs, ys;
bool isval(int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; }
int calc(int x, int y) {
  return max(x / k + (x % k), y / k + (y % k) + (y != 0));
}
void bfs(int x, int y) {
  queue<pair<int, int> > q;
  d[x][y] = {0, 0};
  q.push({x, y});
  while (q.size()) {
    pair<int, int> t = q.front();
    q.pop();
    x = t.first;
    y = t.second;
    mark[x][y] = true;
    if (isval(x + 1, y) && !mark[x + 1][y]) {
      int tmp1 = d[x][y].first;
      int tmp2 = d[x][y].second;
      tmp1++;
      if (a[x + 1][y] == '#') {
        tmp2++;
      }
      if (calc(tmp1, tmp2) < calc(d[x + 1][y].first, d[x + 1][y].second)) {
        d[x + 1][y].first = tmp1;
        d[x + 1][y].second = tmp2;
        q.push({x + 1, y});
      }
    }
    if (isval(x - 1, y) && !mark[x - 1][y]) {
      int tmp1 = d[x][y].first;
      int tmp2 = d[x][y].second;
      tmp1++;
      if (a[x - 1][y] == '#') {
        tmp2++;
      }
      if (calc(tmp1, tmp2) < calc(d[x - 1][y].first, d[x - 1][y].second)) {
        d[x - 1][y].first = tmp1;
        d[x - 1][y].second = tmp2;
        q.push({x - 1, y});
      }
    }
    if (isval(x, y + 1) && !mark[x][y + 1]) {
      int tmp1 = d[x][y].first;
      int tmp2 = d[x][y].second;
      tmp1++;
      if (a[x][y + 1] == '#') {
        tmp2++;
      }
      if (calc(tmp1, tmp2) < calc(d[x][y + 1].first, d[x][y + 1].second)) {
        d[x][y + 1].first = tmp1;
        d[x][y + 1].second = tmp2;
        q.push({x, y + 1});
      }
    }
    if (isval(x, y - 1) && !mark[x][y - 1]) {
      int tmp1 = d[x][y].first;
      int tmp2 = d[x][y].second;
      tmp1++;
      if (a[x][y - 1] == '#') {
        tmp2++;
      }
      if (calc(tmp1, tmp2) < calc(d[x][y - 1].first, d[x][y - 1].second)) {
        d[x][y - 1].first = tmp1;
        d[x][y - 1].second = tmp2;
        q.push({x, y - 1});
      }
    }
  }
}
int main() {
  cin >> n >> m >> k;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      d[i][j].first = d[i][j].second = 10000;
      cin >> a[i][j];
      if (a[i][j] == 'S') {
        xs = i;
        ys = j;
      }
    }
  }
  bfs(xs, ys);
  int ans = 1e9;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {
        int tmp = calc(d[i][j].first, d[i][j].second);
        ans = min(ans, tmp);
      }
    }
  }
  cout << ans << endl;
}
