import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, std.container, std.range;

void main()
{
    auto hwk = readln.split.to!(int[]);
    auto H = hwk[0];
    auto W = hwk[1];
    auto K = hwk[2];
    auto MAP = new char[][](H, W);
    auto MEMO = new int[][](H, W);
    foreach (ref memo; MEMO) memo[] = int.max;
    int sx, sy;
    foreach (i; 0..H) foreach (j, c; readln.chomp.to!(char[])) {
        if (c == 'S') {
            sx = j.to!int;
            sy = i;
            c = '.';
            MEMO[i][j] = 1;
        }
        MAP[i][j] = c;
    }
    auto ss = [[sx, sy]];
    foreach (_; 0..K) {
        int[][] nss;
        foreach (s; ss) {
            auto x = s[0];
            auto y = s[1];
            static foreach (d; [[1,0], [0,1], [-1,0], [0,-1]]) {{
                auto xx = x+d[0];
                auto yy = y+d[1];
                if (0 <= xx && xx < W && 0 <= yy && yy < H && MAP[yy][xx] == '.' && MEMO[yy][xx] > 1) {
                    MEMO[yy][xx] = 1;
                    nss ~= [xx, yy];
                    if (xx == 0 || xx == W-1 || yy == 0 || yy == H-1) {
                        writeln(1);
                        return;
                    }
                }
            }}
        }
        ss = nss;
    }
    ss = [];
    foreach (i; 0..H) foreach (j; 0..W) if (MEMO[i][j] == 1) ss ~= [i, j];
    foreach (t; 2..1000000) {
        foreach (_; 0..K) {
            int[][] nss;
            foreach (s; ss) {
                auto x = s[0];
                auto y = s[1];
                static foreach (d; [[1,0], [0,1], [-1,0], [0,-1]]) {{
                    auto xx = x+d[0];
                    auto yy = y+d[1];
                    if (0 <= xx && xx < W && 0 <= yy && yy < H && MEMO[yy][xx] > t) {
                        MEMO[yy][xx] = t;
                        nss ~= [xx, yy];
                        if (xx == 0 || xx == W-1 || yy == 0 || yy == H-1) {
                            writeln(t);
                            return;
                        }
                    }
                }}
            }
            ss = nss;
        }
    }
}