#include <bits/stdc++.h>
using namespace std;
char str[888][888];
int sx, sy;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
struct node {
  int x, y;
};
int dp[888][888];
int vis[888][888];
int h, w, k;
void BFS() {
  node a, b, c;
  a.x = sx;
  a.y = sy;
  queue<node> que;
  while (!que.empty()) que.pop();
  que.push(a);
  vis[a.x][a.y] = 1;
  int f = 0;
  while (!que.empty()) {
    b = que.front();
    que.pop();
    for (int i = 0; i < 4; i++) {
      c.x = b.x + dx[i];
      c.y = b.y + dy[i];
      if (c.x >= 0 && c.x < h && c.y >= 0 && c.y < w && !vis[c.x][c.y]) {
        vis[c.x][c.y] = 1;
        if (str[c.x][c.y] != str[b.x][b.y]) {
          dp[c.x][c.y] = dp[b.x][b.y] + 1;
          f = 0;
        } else {
          f++;
          if (f == k) {
            dp[c.x][c.y] = dp[b.x][b.y] + 1;
            f = 0;
          } else {
            dp[c.x][c.y] = dp[b.x][b.y];
          }
        }
        que.push(c);
      }
    }
  }
}
int main() {
  scanf("%d %d %d", &h, &w, &k);
  for (int i = 0; i < h; i++) {
    scanf("%s", str[i]);
    for (int j = 0; j < w; j++) {
      if (str[i][j] == 'S') {
        sx = i;
        sy = j;
      }
    }
  }
  str[sx][sy] = '.';
  BFS();
  int mins = 12345678;
  for (int i = 0; i < w; i++) {
    mins = min(mins, dp[0][i] + 1);
    mins = min(mins, dp[h - 1][i] + 1);
  }
  for (int i = 0; i < h; i++) {
    mins = min(mins, dp[i][0] + 1);
    mins = min(mins, dp[i][w - 1] + 1);
  }
  cout << mins << endl;
  return 0;
}
