Problem:
Score : 600 points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..

In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

Constraints

1 \leq H,W,K \leq 10^6

H \times W \leq 10^6

1 \leq x_1,x_2 \leq H

1 \leq y_1,y_2 \leq W

x_1 \neq x_2 or y_1 \neq y_2.

c_{i,j} is . or @.

c_{x_1,y_1} = .

c_{x_2,y_2} = .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

H W K
x_1 y_1 x_2 y_2
c_{1,1}c_{1,2} .. c_{1,W}
c_{2,1}c_{2,2} .. c_{2,W}
:
c_{H,1}c_{H,2} .. c_{H,W}

Output

Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:

From (3, 2), go west one square to (3, 1).

From (3, 1), go north two squares to (1, 1).

From (1, 1), go east two squares to (1, 3).

From (1, 3), go east one square to (1, 4).

From (1, 4), go south two squares to (3, 4).

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1

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

use std::collections::BinaryHeap;
 
type BoxResult<T> = Result<T, Box<std::error::Error>>;
 
 
fn main() {
    let mut scanner = Scanner::new(stdin());
    let (h, w, k) = scanner.read_three::<usize, usize, usize>().unwrap();
    let (x1, y1, x2, y2) = scanner.read_four::<usize, usize, usize, usize>().unwrap();
    let mut grid = vec![vec![false; w + 2]; h + 2];
    for i in 1..(h + 1) {
        let line = scanner.read_chars().unwrap();
        for j in 0..w {
            if line[j] == '@' {
                continue;
            }
            grid[i][j + 1] = true;
        }
    }
    if let Some(ans) = solve(h, w, k, x1, y1, x2, y2, &grid) {
        println!("{}", ans);
    } else {
        println!("-1");
    }
}
 
fn solve(h: usize, w: usize, k: usize, x1: usize, y1: usize, x2: usize, y2: usize, grid: &[Vec<bool>]) -> Option<usize> {
    let dir = vec![(0, !0), (0, 1), (!0, 0), (1, 0)];
    let mut dists = vec![vec![vec![std::usize::MAX; 4]; w + 2]; h + 2];
    let mut queue = BinaryHeap::new();
    queue.push(encode(x1, y1, 0, 0, 0));
    while queue.len() > 0 {
        let (x, y, d, r, i) = decode(queue.pop().unwrap());
        if dists[x][y][i] != std::usize::MAX {
            continue;
        }
        let c = ceil(d, r, k);
        dists[x][y][i] = c;
        for (j, &(dx, dy)) in dir.iter().enumerate() {
            if j != i {
                if dists[x][y][j] == std::usize::MAX {
                    queue.push(encode(x, y, ceil(d, r, k), 0, j));
                }
                continue;
            }
            let nx = x.wrapping_add(dx);
            let ny = y.wrapping_add(dy);
            if nx < 1 || nx > h || ny < 1 || ny > w {
                continue;
            }
            if !grid[nx][ny] {
                continue;
            }
            if dists[nx][ny][j] != std::usize::MAX {
                continue;
            }
            queue.push(encode(nx, ny, d + (r + 1) / k, (r + 1) % k, j));
        }
    }
    let d = dists[x2][y2][0];
    if d == std::usize::MAX {
        None
    } else {
        Some(d)
    }
}

fn encode(x: usize, y: usize, d: usize, r: usize, i: usize) -> (i64, i64, usize, usize, usize) {
    (-(d as i64), -(r as i64), x, y, i)
}

fn decode(key: (i64, i64, usize, usize, usize)) -> (usize, usize, usize, usize, usize) {
    (key.2, key.3, (-key.0) as usize, (-key.1) as usize, key.4)
}

fn ceil(d: usize, r: usize, k: usize) -> usize {
    d + (r + k - 1) / k
}
 
 
use std::error::Error;
use std::fmt::Debug;
use std::str::FromStr;
use std::io::prelude::*;
use std::io::{stdin,  BufReader};
 
pub struct Scanner<R> {
    reader: BufReader<R>,
    buffer: String,
}
impl<R> Scanner<R>
where
    R: Read,
{
    pub fn new(inner: R) -> Scanner<R> {
        let reader = BufReader::new(inner);
        let buffer = String::new();
        Scanner {
            reader: reader,
            buffer: buffer,
        }
    }
    pub fn with_capacity(capacity: usize, inner: R) -> Scanner<R> {
        let reader = BufReader::with_capacity(capacity, inner);
        let buffer = String::new();
        Scanner {
            reader: reader,
            buffer: buffer,
        }
    }
    pub fn read_line(&mut self) -> BoxResult<String> {
        self.reader.read_line(&mut self.buffer)?;
        let cloned = self.buffer.trim().to_string();
        self.buffer.clear();
        Ok(cloned)
    }
 
    pub fn read<T>(&mut self) -> BoxResult<T>
    where
        T: FromStr,
        T::Err: Debug + Error + 'static,
    {
        self.reader.read_line(&mut self.buffer)?;
        let parsed = self.buffer.trim().parse()?;
        self.buffer.clear();
        Ok(parsed)
    }
    pub fn read_two<T, U>(&mut self) -> BoxResult<(T, U)>
    where
        T: FromStr + Copy,
        T::Err: Debug + Error + 'static,
        U: FromStr + Copy,
        U::Err: Debug + Error + 'static,
    {
        self.reader.read_line(&mut self.buffer)?;
        let (a, b) = {
            let params = self.buffer.trim().split_whitespace().collect::<Vec<_>>();
            let a = params[0].parse()?;
            let b = params[1].parse()?;
            (a, b)
        };
        self.buffer.clear();
        Ok((a, b))
    }
    pub fn read_three<T, U, V>(&mut self) -> BoxResult<(T, U, V)>
    where
        T: FromStr + Copy,
        T::Err: Debug + Error + 'static,
        U: FromStr + Copy,
        U::Err: Debug + Error + 'static,
        V: FromStr + Copy,
        V::Err: Debug + Error + 'static,
    {
        self.reader.read_line(&mut self.buffer)?;
        let (a, b, c) = {
            let params = self.buffer.trim().split_whitespace().collect::<Vec<_>>();
            let a = params[0].parse()?;
            let b = params[1].parse()?;
            let c = params[2].parse()?;
            (a, b, c)
        };
        self.buffer.clear();
        Ok((a, b, c))
    }
    pub fn read_four<T, U, V, W>(&mut self) -> BoxResult<(T, U, V, W)>
    where
        T: FromStr + Copy,
        T::Err: Debug + Error + 'static,
        U: FromStr + Copy,
        U::Err: Debug + Error + 'static,
        V: FromStr + Copy,
        V::Err: Debug + Error + 'static,
        W: FromStr + Copy,
        W::Err: Debug + Error + 'static,
    {
        self.reader.read_line(&mut self.buffer)?;
        let (a, b, c, d) = {
            let params = self.buffer.trim().split_whitespace().collect::<Vec<_>>();
            let a = params[0].parse()?;
            let b = params[1].parse()?;
            let c = params[2].parse()?;
            let d = params[3].parse()?;
            (a, b, c, d)
        };
        self.buffer.clear();
        Ok((a, b, c, d))
    }
    pub fn read_vector<T>(&mut self) -> BoxResult<Vec<T>>
    where
        T: FromStr + Copy,
        T::Err: Debug + Error + 'static,
    {
        self.reader.read_line(&mut self.buffer)?;
        let parsed_vec = self
            .buffer
            .trim()
            .split_whitespace()
            .map(|s| s.parse())
            .collect::<Result<Vec<_>, _>>()?;
        self.buffer.clear();
        Ok(parsed_vec)
    }
    pub fn read_matrix<T>(&mut self, lines: u64) -> BoxResult<Vec<Vec<T>>>
    where
        T: FromStr + Copy,
        T::Err: Debug + Error + 'static,
    {
        let mut parsed_matrix = vec![];
        for _ in 0..lines {
            self.reader.read_line(&mut self.buffer)?;
            parsed_matrix.push(
                self.buffer
                    .trim()
                    .split_whitespace()
                    .map(|s| s.parse())
                    .collect::<Result<Vec<_>, _>>()?,
            );
            self.buffer.clear();
        }
        Ok(parsed_matrix)
    }
    pub fn read_chars(&mut self) -> BoxResult<Vec<char>> {
        self.reader.read_line(&mut self.buffer)?;
        let chars = self.buffer.trim().chars().collect::<Vec<_>>();
        self.buffer.clear();
        Ok(chars)
    }
}