Under construction

Still being built. Things may change

Maze Escape

Time limit1sMemory limit512 MB

Summary
On a grid with walls, find the shortest path from start to exit when exactly one wall cell may be removed.
Level

Medium7 of 10

Topics
BFS, Graph, Array
Solved
No attempts yet

Problem

A wizard tricked Hongik and dropped him into an N×MN \times M maze, on cell (Hx,Hy)(Hx, Hy). Hongik does know where the maze exit is: cell (Ex,Ey)(Ex, Ey). Walls the wizard put up stand all over the maze, so walking out is not easy.

Hongik carries a wand he stole from the wizard's workshop, and the wand turns one wall cell into an empty cell. The wand works only once.

Hongik moves only to a cell that shares a side with the cell he is on, and every move takes the same amount of time. Breaking a wall takes no time. Decide whether Hongik can escape the maze, and if he can, find DD, the number of moves on the fastest route.

Input

N M
Hx Hy
Ex Ey

The maze follows on NN lines starting with the fourth line. Each line holds MM integers separated by spaces, where 0 is an empty cell and 1 is a wall.

  • 2≤N≤10002 \le N \le 1000, 2≤M≤10002 \le M \le 1000
  • 1≤Hx,Ex≤N1 \le Hx, Ex \le N, 1≤Hy,Ey≤M1 \le Hy, Ey \le M. HxHx and ExEx are row numbers, HyHy and EyEy are column numbers, and the top left cell is (1,1)(1, 1).
  • (Hx,Hy)≠(Ex,Ey)(Hx, Hy) \neq (Ex, Ey)
  • The start cell and the exit cell are always empty.

Output

Print DD, the smallest number of moves that reaches the exit cell, on one line. If the exit cell stays out of reach even after one use of the wand, print -1.

Hint

In the first example, break the wall at (3,2)(3, 2) to get from the top left cell to the bottom right cell.

Examples3

  1. Example 1

    Input
    5 6
    1 1
    5 6
    0 1 1 1 0 0
    0 1 1 0 0 0
    0 1 0 0 1 0
    0 1 0 0 1 0
    0 0 0 1 1 0
    
    Expected output
    11
    
  2. Example 2

    Input
    2 2
    1 1
    2 2
    0 0
    0 0
    
    Expected output
    2
    
  3. Example 3

    Input
    2 2
    1 1
    2 2
    0 1
    1 0
    
    Expected output
    2