#include <bits/stdc++.h>
using namespace std;
long long h, w, k;
long long dx[]{1, 0, -1, 0};
long long dy[]{0, 1, 0, -1};
char field[801][801];
signed main() {
  cin >> h >> w >> k;
  long long sx;
  long long sy;
  for (long long i = 0; i < h; ++i) {
    for (long long j = 0; j < w; ++j) {
      char c;
      cin >> c;
      if (c == 'S') {
        sx = j;
        sy = i;
      }
      field[i][j] = c;
    }
  }
  long long ans = 0;
  queue<pair<pair<long long, long long>,
             pair<pair<long long, long long>, bool> > >
      que;
  que.push(make_pair(make_pair(sx, sy), make_pair(make_pair(1, 0), false)));
  while (true) {
    auto p = que.front();
    que.pop();
    pair<long long, long long> xy = p.first;
    pair<pair<long long, long long>, long long> zx = p.second;
    long long turn = zx.first.first;
    long long cnt = zx.first.second;
    bool tile = zx.second;
    if (xy.first == 0 || xy.first == w - 1 || xy.second == 0 ||
        xy.second == h - 1) {
      ans = turn;
      break;
    }
    if (cnt != 0 && cnt % k == 0) {
      if (tile == false)
        tile = true;
      else
        tile = false;
      turn++;
    }
    field[xy.first][xy.second] = '-';
    for (long long i = 0; i < 4; ++i) {
      if (h > w && i == 1 || i == 3)
        continue;
      else if (w > h && i == 0 || i == 2)
        continue;
      long long nx = xy.first + dx[i];
      long long ny = xy.second + dy[i];
      if (nx >= 0 && nx < w && ny >= 0 && ny < h) {
        if (field[nx][ny] == '-') continue;
        if (tile) {
          if (field[nx][ny] == '#')
            que.push(make_pair(make_pair(nx, ny),
                               make_pair(make_pair(turn, cnt + 1), tile)));
          else
            que.push(make_pair(make_pair(nx, ny),
                               make_pair(make_pair(turn, cnt), tile)));
        } else {
          if (field[nx][ny] == '.')
            que.push(make_pair(make_pair(nx, ny),
                               make_pair(make_pair(turn, cnt + 1), tile)));
        }
      }
    }
    if (que.empty()) {
      que.push(make_pair(make_pair(xy.first, xy.second),
                         make_pair(make_pair(turn, k), tile)));
    }
  }
  cout << ans << endl;
  return 0;
}
