#include<bits/stdc++.h>
using namespace std;

const int dir[4][2] = {1,0,-1,0,0,1,0,-1};
pair < int , int > dst[803][803];
char Map[803][803]; int H , W , K;
struct data{
	pair < int , int > val; pair < int , int > pos;
	friend bool operator <(data p , data q){return p.val > q.val;}
}; priority_queue < data > q;

int main(){
	memset(dst , 0x3f , sizeof(dst));
	cin >> H >> W >> K;
	for(int i = 1 ; i <= H ; ++i)
		for(int j = 1 ; j <= W ; ++j){
			cin >> Map[i][j];
			if(Map[i][j] == 'S'){
				dst[i][j] = make_pair(0 , 0);
				q.push((data){make_pair(0 , 0) , make_pair(i , j)});
			}
		}
	while(!q.empty()){
		pair < int , int > t = q.top().pos;
		int x = t.first , y = t.second;
		if(x == 1 || y == 1 || x == H || y == W){cout << dst[x][y].first + 1; return 0;}
		q.pop();
		for(int i = 0 ; i < 4 ; ++i){
			int X = x + dir[i][0] , Y = y + dir[i][1];
			pair < int , int > ndst = dst[x][y].first || Map[X][Y] != '#' ? (dst[x][y].second == K ? make_pair(dst[x][y].first + 1 , 1) : make_pair(dst[x][y].first , dst[x][y].second + 1)) : make_pair(1 , 1);
			if(dst[X][Y] > ndst){dst[X][Y] = ndst; q.push((data){dst[X][Y] , make_pair(X , Y)});}
		}
	}
	return 0;
}
