Problem:
Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2

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

#![allow(clippy::needless_range_loop)]
#![allow(unused_macros)]
#![allow(dead_code)]
#![allow(unused_imports)]

use itertools::*;
use proconio::input;
use proconio::marker::*;
use std::cmp::Reverse;

pub trait SafeIndex<T> {
    fn at(&self, index: isize) -> Option<&T>;
    fn at_d(&self, index: isize) -> &T {
        self.at(index).unwrap()
    }
}
impl<T> SafeIndex<T> for Vec<T> {
    fn at(&self, index: isize) -> Option<&T> {
        let length = self.len() as isize;
        if 0 <= index && index < length {
            Some(&self[index as usize])
        } else {
            None
        }
    }
}
impl<T> SafeIndex<T> for &[T] {
    fn at(&self, index: isize) -> Option<&T> {
        let length = self.len() as isize;
        if 0 <= index && index < length {
            Some(&self[index as usize])
        } else {
            None
        }
    }
}
impl<T> SafeIndex<T> for &mut [T] {
    fn at(&self, index: isize) -> Option<&T> {
        let length = self.len() as isize;
        if 0 <= index && index < length {
            Some(&self[index as usize])
        } else {
            None
        }
    }
}
pub trait SafeIndexMut<T> {
    fn at_mut(&mut self, index: isize) -> Option<&mut T>;
}
impl<T> SafeIndexMut<T> for Vec<T> {
    fn at_mut(&mut self, index: isize) -> Option<&mut T> {
        let length = self.len() as isize;
        if 0 <= index && index < length {
            Some(&mut self[index as usize])
        } else {
            None
        }
    }
}
impl<T> SafeIndexMut<T> for &mut [T] {
    fn at_mut(&mut self, index: isize) -> Option<&mut T> {
        let length = self.len() as isize;
        if 0 <= index && index < length {
            Some(&mut self[index as usize])
        } else {
            None
        }
    }
}

fn color(mut c: &mut[Vec<usize>], s: &[Vec<u8>], x: isize, y: isize, col: usize) {
    if let Some(ch) = c.at_mut(y) {
        if let Some(item) = ch.at_mut(x) {
            if *s.at_d(y).at_d(x) == b'#' || *item != 1234567 {
                return;
            }
            *item = col;
            color(c, s, x - 1, y, col);
            color(c, s, x + 1, y, col);
            color(c, s, x, y - 1, col);
            color(c, s, x, y + 1, col);
        }
    }
}

use std::cmp::*;
use std::collections::binary_heap::BinaryHeap;
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct GraphEdge {
    node_to: usize,
    cost: isize,
}
impl Ord for GraphEdge {
    fn cmp(&self, other: &GraphEdge) -> Ordering {
        other.cost.cmp(&self.cost)
    }
}
impl PartialOrd for GraphEdge {
    fn partial_cmp(&self, other: &GraphEdge) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
impl GraphEdge {
    pub fn new(node_to: usize, cost: isize) -> Self {
        Self { node_to, cost }
    }
}
pub struct Graph {
    pub edges: Vec<Vec<GraphEdge>>,
    pub nodes: usize,
}
impl Graph {
    pub fn new(nodes: usize) -> Self {
        Self {
            edges: vec![vec![]; nodes],
            nodes,
        }
    }
    pub fn edge_undirected(&mut self, node_a: usize, node_b: usize) {
        self.edges[node_a].push(GraphEdge::new(node_b, 1));
        self.edges[node_b].push(GraphEdge::new(node_a, 1));
    }
    pub fn edge_directed(&mut self, node_from: usize, node_to: usize) {
        self.edges[node_from].push(GraphEdge::new(node_to, 1));
    }
    pub fn edge_undirected_costed(&mut self, node_a: usize, node_b: usize, cost: isize) {
        self.edges[node_a].push(GraphEdge::new(node_b, cost));
        self.edges[node_b].push(GraphEdge::new(node_a, cost));
    }
    pub fn edge_directed_costed(&mut self, node_from: usize, node_to: usize, cost: isize) {
        self.edges[node_from].push(GraphEdge::new(node_to, cost));
    }
    pub fn dijkstra(&self, node_from: usize) -> Vec<isize> {
        let mut costs = vec![std::isize::MAX; self.nodes];
        let mut heap: BinaryHeap<GraphEdge> = BinaryHeap::new();
        heap.push(GraphEdge::new(node_from, 0));
        while let Some(GraphEdge { cost, node_to }) = heap.pop() {
            if cost >= costs[node_to] {
                continue;
            }
            costs[node_to] = cost;
            for edge in &self.edges[node_to] {
                let next = GraphEdge::new(edge.node_to, cost + edge.cost);
                heap.push(next);
            }
        }
        costs
    }
    pub fn warshall_floyd(&self) -> Vec<Vec<isize>> {
        let mut costs = vec![vec![std::isize::MAX; self.nodes]; self.nodes];
        for i in 0..self.nodes {
            costs[i][i] = 0;
        }
        for (node_from, edges) in self.edges.iter().enumerate() {
            for GraphEdge { node_to, cost } in edges.iter() {
                costs[node_from][*node_to] = *cost;
            }
        }
        for k in 0..self.nodes {
            for i in 0..self.nodes {
                for j in 0..self.nodes {
                    costs[i][j] =
                        std::cmp::min(costs[i][j], costs[i][k].saturating_add(costs[k][j]));
                }
            }
        }
        costs
    }
}

fn main() {
    input! {
        h: isize,
        w: isize,
        c: (Usize1, Usize1),
        d: (Usize1, Usize1),
        s: [Bytes; h]
    }

    let mut col = 0;
    let mut colored = vec![vec![1234567; w as usize]; h as usize];
    for (x, y) in iproduct!(0..w, 0..h) {
        if *colored.at_d(y).at_d(x) == 1234567 && *s.at_d(y).at_d(x) == b'.' {
            color(&mut colored, &s, x as isize, y as isize, col);
            col += 1;
        }
    }
    use std::collections::HashSet;
    use std::cmp::{min, max};
    let mut edges: HashSet<(usize, usize)> = HashSet::new();
    for (x, y) in iproduct!(0..w, 0..h) {
        for (tx, ty) in iproduct!(-2..=2, -2..=2) {
            let tx = x as isize + tx;
            let ty = y as isize + ty;

            let &c = colored.at_d(y).at_d(x);
            if let Some(Some(&tc)) = colored.at(ty).map(|x|x.at(tx)) {
                if tc != c && tc != 1234567 && c != 1234567 {
                    edges.insert((tc, c));
                    edges.insert((c, tc));
                    if tc == 0 && c == 0 {
                        eprintln!("{}, {}, {}, {}", x, y, tx, ty);
                    }
                }
            }
        }
    }

    let mut graph = Graph::new(col);
    for &(a, b) in edges.iter() {
        graph.edge_directed_costed(a, b, 1);
    }

    let from = colored[c.0][c.1];
    let to = colored[d.0][d.1];
    let costs = graph.dijkstra(from);
    let ans = if costs[to] == std::isize::MAX {
        -1
    } else {
        costs[to]
    };

    println!("{}", ans);
}