#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
typedef vector<int> vi;

template<class T> inline T re(){
	T N = 0; char c = getchar(); bool neg = 0;
	for (; c < '0' || c > '9'; c = getchar()) neg |= c == '-';
	for (; c >= '0' && c <= '9'; c = getchar())
		N = (N<<3)+(N<<1) + c - '0';
	return neg ? -N : N;
}

int h, w, k;
inline bool ins(int r, int c){
	return 1 <= r && r <= h && 1 <= c && c <= w;
}
char g[805][805];
pair<int,int> d[805][805];
struct dt{
	int r, c, dm, dk;
	dt(int r=0, int c =0, int dm = 0, int dk = 0):r(r),c(c),dm(dm),dk(dk){}
	bool operator< (const dt &rhs) const{
		return dm == rhs.dm ? dk > rhs.dk : dm > rhs.dm;
	}
};
priority_queue<dt> q;
int dr[] = {1,0,-1,0};
int dc[] = {0,1,0,-1};

void dijk(pii st){
	q.emplace(st.fi, st.se, 0, k);
	memset(d, 0x3f3f3f3f, sizeof(d));
	d[st.fi][st.se] = {0,k};
	while (!q.empty()){
		dt u = q.top(); q.pop();
//		cout << u.r << ' ' << u.c << ' ' << u.dm << ' ' << u.dk << '\n';
		pii D = make_pair(u.dm, u.dk);
		if (D < d[u.r][u.c]) continue;
		for (int i = 0; i < 4; i++){
			pii x = {u.r + dr[i], u.c + dc[i]};
			if (!ins(x.fi, x.se)) continue;
			int dm, dk;
			if (g[x.fi][x.se] == g[u.r][u.c]){
				dk = u.dk + 1; dm = u.dm;
				if (dk == k + 1) dm++, dk = 1;
			} else if (g[x.fi][x.se] == '#'){
				dm = u.dm, dk = 1;
			} else {
				dm = u.dm + 1; dk = 1;
			}
			if (make_pair(dm, dk) < d[x.fi][x.se]){
				d[x.fi][x.se] = {dm, dk};
				q.emplace(x.fi, x.se, dm, dk);
			}
		}
	}
}

int main(){
	scanf("%d %d %d", &h, &w, &k);
	pii st = {-1,-1};
	for (int i = 1; i <= h; i++){
		scanf("%s", g[i] + 1);
		for (int j = 1; j <= w; j++)
			if (g[i][j] == 'S'){
				st = {i, j}; g[i][j] = '#';
			}
	}
	dijk(st);
//	for (int i = 1; i <= h; i++) for(int j = 1; j <= w; j++){
//		printf("(%d, %d)%c", d[i][j].fi, d[i][j].se, " \n"[j==w]);
//	}
	int mn = 0x3f3f3f3f;
	for (int i = 1; i <= h; i++){
		mn = min(mn, d[i][1].fi + (g[i][1] == '#'));
		mn = min(mn, d[i][w].fi + (g[i][w] == '#'));
	}
	for (int i = 1; i <= w; i++){
		mn = min(mn, d[1][i].fi + (g[1][i] == '#'));
		mn = min(mn, d[h][i].fi + (g[h][i] == '#'));
	}
	cout << mn << '\n';
	return 0;
}
