H,W,K=map(int,input().split())
A=[input() for i in range(H)]
for i,l in enumerate(A):
    if 'S' in l:
        S=((1,0,K),i,l.index('S'))
q=[S]
from heapq import heappop,heappush
n=((0,1),(0,-1),(1,0),(-1,0))
v=[[0]*W for i in range(H)]
v[S[1]][S[2]]=1
a=999
#M=[[999]*H for i in range(W)]
while q:
    (s,m,o),i,j=heappop(q)
    #M[i][j]=min(s,M[i][j])
    if i in (0,H-1) or j in (0,W-1):
        a=min(a,s)
    for x,y in n:
        if 0<=i+x<H and 0<=j+y<W:
            if v[i+x][j+y]:continue
            v[i+x][j+y]=1
            if A[i+x][j+y]=='.':
                if m<K:
                    heappush(q,((s,m+1,o),i+x,j+y))
                else:
                    heappush(q,((s+1,1,o-K),i+x,j+y))
            elif A[i+x][j+y]=='#':
                if m<K and o<K:
                    heappush(q,((s,m+1,o+1),i+x,j+y))
                else:
                    heappush(q,((s+1,1,o-K+1),i+x,j+y))
print(a)
#print(*M,sep='\n')