#include <bits/stdc++.h>
using namespace std;
char t[1000][1000];
int lvl[1000][1000], d[1000][1000], ans[1000][1000];
int di[] = {0, 1, 0, -1}, dj[] = {1, 0, -1, 0};
int main() {
  int H, W, K;
  cin >> H >> W >> K;
  int si, sj;
  for (int i = 1; i <= H; ++i) {
    for (int j = 1; j <= W; ++j) {
      cin >> t[i][j];
      if (t[i][j] == 'S') si = i, sj = j;
    }
  }
  for (int i = 0; i <= H; ++i) t[i][0] = t[i][W + 1] = 'E';
  for (int i = 0; i <= W; ++i) t[0][i] = t[H + 1][i] = 'E';
  for (int i = 0; i <= H + 1; ++i) {
    for (int j = 0; j <= W + 1; ++j) {
      lvl[i][j] = d[i][j] = ans[i][j] = -1;
    }
  }
  priority_queue<pair<int, pair<int, int>>> que;
  que.push({0, {si, sj}});
  while (!que.empty()) {
    int dis = -que.top().first, posi = que.top().second.first,
        posj = que.top().second.second;
    que.pop();
    if (lvl[posi][posj] >= 0) continue;
    lvl[posi][posj] = dis / K + (dis % K == 0 ? 0 : 1) + 1;
    if (t[posi][posj] == 'E') continue;
    for (int i = 0; i < 4; ++i) {
      if (lvl[posi + di[i]][posj + dj[i]] >= 0) continue;
      if (t[posi + di[i]][posj + dj[i]] == '#') {
        que.push({-dis - 1, {posi + di[i], posj + dj[i]}});
      } else {
        que.push({-dis, {posi + di[i], posj + dj[i]}});
      }
    }
  }
  que.push({0, {si, sj}});
  while (!que.empty()) {
    int dis = -que.top().first, posi = que.top().second.first,
        posj = que.top().second.second;
    que.pop();
    if (d[posi][posj] >= 0) continue;
    d[posi][posj] = dis / K + (dis % K == 0 ? 0 : 1);
    if (t[posi][posj] == 'E') continue;
    for (int i = 0; i < 4; ++i) {
      if (d[posi + di[i]][posj + dj[i]] >= 0) continue;
      que.push({-dis - 1, {posi + di[i], posj + dj[i]}});
    }
  }
  que.push({0, {si, sj}});
  while (!que.empty()) {
    int dis = -que.top().first, posi = que.top().second.first,
        posj = que.top().second.second;
    que.pop();
    if (ans[posi][posj] >= 0) continue;
    ans[posi][posj] = dis;
    if (t[posi][posj] == 'E') continue;
    for (int i = 0; i < 4; ++i) {
      if (ans[posi + di[i]][posj + dj[i]] >= 0) continue;
      que.push({-max({dis, lvl[posi + di[i]][posj + dj[i]],
                      d[posi + di[i]][posj + dj[i]]}),
                {posi + di[i], posj + dj[i]}});
    }
  }
  int mi = 1e9;
  for (int i = 0; i <= H; ++i) {
    if (ans[i][0] >= 0) mi = min(mi, ans[i][0]);
    if (ans[i][W + 1] >= 0) mi = min(mi, ans[i][W + 1]);
  }
  for (int i = 0; i <= W; ++i) {
    if (ans[0][i] >= 0) mi = min(mi, ans[i][0]);
    if (ans[H + 1][i] >= 0) mi = min(mi, ans[H + 1][i]);
  }
  cout << mi << endl;
  return 0;
}
