#include <bits/stdc++.h>
using namespace std;
int mat[1000][1000];
int memo[1000][1000];
int x, y, n, m;
void BFS() {
  queue<pair<int, int> > q;
  q.push(make_pair(x, y));
  memo[x][y] = 1;
  while (!q.empty()) {
    x = q.front().first;
    y = q.front().second;
    q.pop();
    if (x + 1 < n) {
      if (memo[x + 1][y] == 0 && mat[x + 1][y] == 1) {
        memo[x + 1][y] = memo[x][y] + 1;
        q.push(make_pair(x + 1, y));
      }
    }
    if (x - 1 >= 0) {
      if (memo[x - 1][y] == 0 && mat[x - 1][y] == 1) {
        memo[x - 1][y] = memo[x][y] + 1;
        q.push(make_pair(x - 1, y));
      }
    }
    if (y + 1 < m) {
      if (memo[x][y + 1] == 0 && mat[x][y + 1] == 1) {
        memo[x][y + 1] = memo[x][y] + 1;
        q.push(make_pair(x, y + 1));
      }
    }
    if (y - 1 >= 0) {
      if (memo[x][y - 1] == 0 && mat[x][y - 1] == 1) {
        memo[x][y - 1] = memo[x][y] + 1;
        q.push(make_pair(x, y - 1));
      }
    }
  }
}
int main() {
  int k = 0, step = 0, i = 0, j = 0;
  string s = "";
  cin >> n >> m >> k;
  for (i = 0; i < n; i++) {
    cin >> s;
    for (j = 0; j < m; j++) {
      if (s[j] == '#')
        mat[i][j] = 0;
      else
        mat[i][j] = 1;
      if (s[j] == 'S') {
        x = i;
        y = j;
      }
    }
  }
  BFS();
  bool flag = 0;
  for (i = 0; i < m; i++) {
    if (memo[0][i] != 0 || memo[n - 1][i] != 0) {
      flag = 1;
      break;
    }
  }
  step = INT_MAX;
  if (flag == 1) {
    if (memo[0][i] != 0) step = min(step, memo[0][i]);
    if (memo[n - 1][i] != 0) step = min(step, memo[n - 1][i]);
    step--;
    if (step % k == 0) {
      step /= k;
    } else {
      step /= k;
      step++;
    }
  } else {
    int aux = INT_MAX;
    for (i = 1; i < n - 1; i++) {
      for (j = 0; j < m; j++) {
        if (memo[i][j] != 0) {
          step = min(step, i);
          step = min(step, (n - 1) - i);
          aux = min(aux, memo[i][j]);
        }
      }
    }
    aux--;
    if (aux % k == 0) {
      aux /= k;
    } else {
      aux /= k;
      aux++;
    }
    if (step % k == 0) {
      step /= k;
    } else {
      step /= k;
      step++;
    }
    step *= 2;
    step += aux;
  }
  cout << step << endl;
  return 0;
}
