# coding: utf-8
# Your code here!
import heapq as hq
H,W,K = map(int,input().split())
A = []
X,Y=0,1
start = None
for h in range(H):
    tmp = list(input())
    A.append(tmp)
    if "S" in tmp:
        start = (tmp.index("S"), h)

def minCost(x,y):
    return min(start[X], W-1-start[X], start[Y], H-1-start[Y]) // K
search = []
searched = [[False for w in range(W)] for h in range(H)]
hq.heapify(search)
hq.heappush(search, (minCost(start[X],start[Y]),0,0,0,start))
vector = [(1,0),(-1,0),(0,1),(0,-1)]
while len(search) > 0:
    _, cost, wall, walk, pos = hq.heappop(search)
    x,y = pos[X], pos[Y]
    if searched[y][x]:
        continue
    if x == 0 or x == W-1 or y == 0 or y == H-1:
        print(cost)
        break
    searched[y][x] = True
    for v in vector:
        new_x,new_y = x+v[X], y+v[Y]
        if not searched[new_y][new_x]:
            new_cost, new_wall, new_walk = cost, wall, walk
            if A[new_y][new_x] == "#":
                new_wall += 1
                if new_wall > 0:
                    new_cost += 1
                    new_wall = -K+1
            new_walk += 1
            if new_walk > 0:
                new_cost += 1
                new_walk = -K+1
            hq.heappush(search, (new_cost + minCost(new_x, new_y), new_cost, new_wall, new_walk, (new_x, new_y)))