import heapq
h,w,k = map(int,input().split())
l = []
for i in range(h):
    a = list(input())
    for j in range(w):
        if a[j] == "S":
            s = [0,[i,j],0,0]
    l.append(a)
ans = h*w
dp = [[[h*w,0,0] for i in range(w)] for i in range(h)]
dp[s[1][0]][s[1][1]] = [0,0,0]
d = [s]
b = [[0,1],[1,0],[-1,0],[0,-1]]
heapq.heapify(d)
while len(d):
    spell1,now,steps1,op1 = heapq.heappop(d)
    if ans < spell1:
        break
    for i in b:
        spell = spell1
        steps = steps1
        op = op1
        #print(now[0]+i[0],now[1]+i[1])
        nex = [now[0]+i[0],now[1]+i[1]]
        if l[nex[0]][nex[1]] == ".":
            if steps > 0:
                steps -= 1
            else:
                spell += 1
                steps += k-1
        else:
            if op > 0:
                if steps > 0:
                    steps -= 1
                    op -= 1
                else:
                    op -= 1
                    steps += k-1
                    spell += 1
            else:
                if steps == 0:
                    steps += k-1
                    spell += 2
                    op += k-1
                else:
                    op += k-1
                    steps += k-1
                    spell += 1
        if nex[0] == 0 or nex[0] == h-1 or nex[1] == 0 or nex[1] == w-1:
            ans = min(ans,spell)
        else:
            dp0 = dp[nex[0]][nex[1]]
            if dp0[0] > spell:
                dp[nex[0]][nex[1]] = [spell,steps,op]
                heapq.heappush(d,[spell,nex,steps,op])
print(ans)