#include<iomanip>
#include<limits>
#include<thread>
#include<utility>
#include<iostream>
#include<string>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<numeric>
#include<cassert>
#include<random>
#include<chrono>
#include<unordered_map>
#include<fstream>
#include<list>
#include<functional>
#include<bitset>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
typedef pair<ll,ll> pll;
typedef pair<int,int> pi;
typedef pair<double,double> pd;
typedef pair<double,ll> pdl;
#define F first
#define S second
const ll E=1e18+7;
const ll MOD=1000000007;


int main(){
    ll h,w,k;
    cin>>h>>w>>k;
    vector<string> A(h);
    for(int i=0;i<h;i++){cin>>A[i];}
    pll s;
    for(int i=0;i<h;i++){
        for(int t=0;t<w;t++){
            if(A[i][t]=='S'){s={i,t};}
        }
    }
    ll ans=E;
    queue<pll> Q;
    Q.push(s);
    vector<vector<ll>> dist(h,vector<ll>(w,E));
    dist[s.F][s.S]=0;
    vector<pll> d={{0,1},{1,0},{-1,0},{0,-1}};
    bool done=false;
    while(!Q.empty() && !done){
        pll W=Q.front(); Q.pop();
        if(dist[W.F][W.S]>=k){continue;}
        for(int i=0;i<4 && !done;i++){
            pll k=W;
            k.F+=d[i].F;
            k.S+=d[i].S;
            if(A[k.F][k.S]=='#' || dist[k.F][k.S]!=E){continue;}
            dist[k.F][k.S]=dist[W.F][W.S]+1;
            Q.push({k.F,k.S});
            if(k.F==0 || k.S==0 || k.F==h-1 || k.S==w-1){
                ans=dist[k.F][k.S];
                done=true;
            }
        }
    }
    for(int i=0;i<h;i++){
        for(int t=0;t<w;t++){
            if(dist[i][t]!=E){
                ans=min(min(ans,k+i),min(k+t,w-1-t+k),min(h-1-i+k,ans));
            }
        }
    }
    cout<<ans<<endl;
    
    
    
    return 0;
}
