problems / 136

Alice's Knight Errand

medium bfs graphs shortest-paths 1000 ms · 256 MB

Alice's Knight Errand

Alice has a letter for Bob, and she trusts only her chess knight to carry it. The knight stands on Alice's square of an n × m board, and Bob waits on another square. Some squares are covered with spilled ink, and the knight refuses to land on them, although it happily leaps over anything in its way. Alice wants the letter delivered as quickly as possible.

Rows are numbered 1 to n from top to bottom and columns 1 to m from left to right. In one move the knight goes from square (r, c) to a square (r + dr, c + dc) where (|dr|, |dc|) is (1, 2) or (2, 1). The destination must lie on the board and must not be blocked; the squares in between do not matter.

Find the minimum number of moves the knight needs to get from Alice's square to Bob's square, or report that it is impossible.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns.

The second line contains four integers r_A, c_A, r_B, c_B (1 ≤ r_A, r_B ≤ n, 1 ≤ c_A, c_B ≤ m) — Alice's square and Bob's square. They may coincide.

Each of the next n lines contains a string of m characters, each . (a free square) or # (a blocked square). The c-th character of the r-th of these lines describes square (r, c). Alice's and Bob's squares are always free.

Output

Print one integer — the minimum number of knight moves from Alice's square to Bob's square, or -1 if the knight cannot reach Bob's square.

Notes

In the first example, one fastest route is (1, 1) → (3, 2) → (5, 3) → (4, 5): three moves. The knight jumps past the blocked square (4, 2) on its second move without any trouble; it only may not land on blocked squares.

In the second example, a knight starting in the corner of a 3 × 3 board can only ever reach the eight border squares, so the centre is unreachable.

Example 1

Input

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

Output

3

Example 2

Input

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

Output

-1

Hints · reveal one at a time if you're stuck

Hint 1

Each knight move costs the same, so think of the board as a graph of free squares where a move is an edge. Which search finds the fewest moves in an unweighted graph, and does a blocked square in the middle of a jump matter?

Hint 2

Run a breadth-first search from Alice's square over the eight knight offsets, skipping squares off the board or blocked. Mark squares when you enqueue them, and print -1 if Bob's square is never reached.

report an issue Prefer your own editor? sooks prep 136 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.