#include <bits/stdc++.h>
using namespace std;
const int INF = 2147483647;
const long long INFL = 9223372036854775807LL;
const double EPSILON = 0.00000001;
const long long MOD = 1000000007;
int H, W, K;
bool is_open[805][805], is_reachable[805][805];
bool visited[805][805];
bool visited2[805][805];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
struct cell {
  int x, y;
  int steps;
  cell() {}
  cell(int x, int y) : x(x), y(y), steps(0) {}
  cell(int x, int y, int steps) : x(x), y(y), steps(steps) {}
};
bool operator<(const cell &a, const cell &b) { return a.steps > b.steps; }
queue<cell> *open, *open_next;
priority_queue<cell> opened;
priority_queue<cell> reached;
int unlock_rooms(int max_step) {
  int num_unlocked = 0;
  while (!opened.empty()) {
    cell top = opened.top();
    if (top.steps > max_step) {
      return num_unlocked;
    }
    opened.pop();
    num_unlocked++;
    is_open[top.y][top.x] = true;
    for (int i = 0; i < 4; i++) {
      cell next = cell(top.x + dx[i], top.y + dy[i], top.steps);
      if (0 <= next.x && next.x < W && 0 <= next.y && next.y < H &&
          !visited[next.y][next.x]) {
        visited[next.y][next.x] = true;
        if (!is_open[next.y][next.x]) next.steps++;
        opened.push(next);
      }
    }
  }
  return num_unlocked;
}
bool travel(int max_step) {
  while (!reached.empty()) {
    cell top = reached.top();
    if (top.steps > max_step) {
      return false;
    }
    reached.pop();
    if (top.x == 0 || top.x == W - 1 || top.y == 0 || top.y == H - 1)
      return true;
    if (!is_open[top.y][top.x]) {
      top.steps = max_step + 1;
      reached.push(top);
      continue;
    }
    is_reachable[top.y][top.x] = true;
    for (int i = 0; i < 4; i++) {
      cell next = cell(top.x + dx[i], top.y + dy[i], top.steps + 1);
      if (0 <= next.x && next.x < W && 0 <= next.y && next.y < H &&
          !visited2[next.y][next.x]) {
        if (!is_open[next.y][next.x]) {
          next.steps = max_step + 1;
        }
        visited2[next.y][next.x] = true;
        reached.push(next);
      }
    }
  }
  return false;
}
int main() {
  scanf("%d %d %d", &H, &W, &K);
  cell start;
  for (int y = 0; y < H; y++) {
    string row;
    cin >> row;
    for (int x = 0; x < (int)(row).size(); x++) {
      is_open[y][x] = (row[x] != '#');
      if (row[x] == 'S') {
        start = cell(x, y);
      }
    }
  }
  memset(visited, false, sizeof(visited));
  ;
  memset(visited2, false, sizeof(visited2));
  ;
  memset(is_reachable, false, sizeof(is_reachable));
  ;
  visited[start.y][start.x] = true;
  visited2[start.y][start.x] = true;
  opened.push(cell(start.x, start.y, 0));
  reached.push(cell(start.x, start.y, 0));
  int steps = 0;
  int max_step = K;
  bool done = false;
  while (!done && steps < 5) {
    done = travel(max_step);
    ;
    unlock_rooms(max_step);
    steps++;
    max_step += K;
  }
  cout << steps << endl;
  return 0;
}
