Problem:
Score : 700 points

Problem Statement

Takahashi is locked within a building.

This building consists of H×W rooms, arranged in H rows and W columns.
We will denote the room at the i-th row and j-th column as (i,j). The state of this room is represented by a character A_{i,j}. If A_{i,j}= #, the room is locked and cannot be entered; if A_{i,j}= ., the room is not locked and can be freely entered.
Takahashi is currently at the room where A_{i,j}= S, which can also be freely entered.

Each room in the 1-st row, 1-st column, H-th row or W-th column, has an exit.
Each of the other rooms (i,j) is connected to four rooms: (i-1,j), (i+1,j), (i,j-1) and (i,j+1).

Takahashi will use his magic to get out of the building. In one cast, he can do the following:

Move to an adjacent room at most K times, possibly zero. Here, locked rooms cannot be entered.

Then, select and unlock at most K locked rooms, possibly zero. Those rooms will remain unlocked from then on.

His objective is to reach a room with an exit. Find the minimum necessary number of casts to do so.

It is guaranteed that Takahashi is initially at a room without an exit.

Constraints

3 ≤ H ≤ 800

3 ≤ W ≤ 800

1 ≤ K ≤ H×W

Each A_{i,j} is # , . or S.

There uniquely exists (i,j) such that A_{i,j}= S, and it satisfies 2 ≤ i ≤ H-1 and 2 ≤ j ≤ W-1.

Input

Input is given from Standard Input in the following format:

H W K
A_{1,1}A_{1,2}...A_{1,W}
:
A_{H,1}A_{H,2}...A_{H,W}

Output

Print the minimum necessary number of casts.

Sample Input 1

3 3 3
#.#
#S.
###

Sample Output 1

1

Takahashi can move to room (1,2) in one cast.

Sample Input 2

3 3 3
###
#S#
###

Sample Output 2

2

Takahashi cannot move in the first cast, but can unlock room (1,2).
Then, he can move to room (1,2) in the next cast, achieving the objective in two casts.

Sample Input 3

7 7 2
#######
#######
##...##
###S###
##.#.##
###.###
#######

Sample Output 3

2

Solution in Rust (1.15.1) (judge verdict: Accepted)

use std::io::{stdin, Read, StdinLock};
use std::str::FromStr;
use std::iter::FromIterator;
use std::collections::VecDeque;
use std::cmp::min;

fn main() {
    let cin = stdin();
    let mut scan = Scanner::new(cin.lock());
    let h = scan.read::<usize>();
    let w = scan.read::<usize>();
    let k = scan.read::<usize>();
    let a = arr(h, |_| scan.chars());
    let mut s = 0;
    for y in 0..h { for x in 0..w {if a[y][x]=='S' {s = y * w + x;}}}
    let mut que = VecDeque::new();
    que.push_back((s, 0));
    let mut used = vec![vec![(false, 0);w];h];
    used[s/w][s%w] = (true, 0);
    while let Some((pos, cnt)) = que.pop_front() {
        let y = pos/w;
        let x = pos%w;
        for (ny, nx) in adjacent4(y, x, h, w) {
            if a[ny][nx] != '#' && !used[ny][nx].0 {
                used[ny][nx] = (true, cnt+1);
                if cnt+1<k {
                    que.push_back((ny * w + nx, cnt + 1));
                }
            }
        }
    }
    let mut ret = 1i64 << 60;
    for y in 0..h {
        for x in 0..w {
            if used[y][x].0 {
                if used[y][x].1 < k  {
                    if y == 0 || y == h-1 || x == 0 || x == w-1 {
                        println!("1");
                        return;
                    }
                }
                let c = min(min(min(x, w-1-x), y), h-1-y);
                ret = min(ret, ceil_div( ui(c) , ui(k)) + 1);
            }
        }
    }
    println!("{}", ret);
}

#[allow(dead_code)]
fn ceil_div(x: i64, y: i64) -> i64 {
    (x + y - 1) / y
}

/// https://github.com/hatoo/competitive-rust-snippets
#[allow(dead_code)]
fn adjacent4(y: usize, x: usize, h: usize, w: usize) -> Box<Iterator<Item = (usize, usize)>> {
    // This code looks verbose but is needed to Rust 1.15.
    static DYDX: [(isize, isize); 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)];

    Box::new(DYDX.iter().filter_map(move |&(dy, dx)| {
        let ny = y as isize + dy;
        let nx = x as isize + dx;
        if nx >= 0 && nx < w as isize && ny >= 0 && ny < h as isize {
            Some((ny as usize, nx as usize))
        } else {
            None
        }
    }))
}

// region template
#[allow(dead_code)]
fn iu(i: i64) -> usize { i as usize }

#[allow(dead_code)]
fn ui(i: usize) -> i64 { i as i64 }

#[allow(dead_code, deprecated)]
fn join<T: std::fmt::Display>(slice: &[T], sep: &str) -> String {
    let strings = slice.iter().map(|t| format!("{}", t)).collect::<Vec<_>>();
    strings.connect(sep)
}

#[allow(dead_code)]
fn arr<'a, S, T>(n: usize, mut f: S) -> Vec<T> where S: FnMut(usize) -> T + 'a {
    (0..n).map(|i| f(i)).collect::<Vec<T>>()
}

#[allow(dead_code)]
fn alt<S, T>(v: Vec<S>) -> T where T: FromIterator<S> {
    v.into_iter().collect::<T>()
}

#[allow(dead_code)]
fn dup<S, T>(v: &[S]) -> T where T: FromIterator<S>, S: Clone {
    v.iter().cloned().collect::<T>()
}

struct Scanner<'a> {
    cin: StdinLock<'a>,
}

#[allow(dead_code)]
impl<'a> Scanner<'a> {
    fn new(cin: StdinLock<'a>) -> Scanner<'a> {
        Scanner { cin: cin }
    }

    fn read1<T: FromStr>(&mut self) -> Option<T> {
        let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>();
        token.parse::<T>().ok()
    }

    fn read<T: FromStr>(&mut self) -> T {
        self.read1().unwrap()
    }

    fn readn<T: FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read::<T>()).collect()
    }

    fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}
// endregion