Maze Escape
Time limit1sMemory limit512 MB
On a grid with walls, find the shortest path from start to exit when exactly one wall cell may be removed.
Problem
A wizard tricked Hongik and dropped him into an maze, on cell . Hongik does know where the maze exit is: cell . 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 , the number of moves on the fastest route.
Input
N M
Hx Hy
Ex Ey
The maze follows on lines starting with the fourth line. Each line holds integers separated by spaces, where 0 is an empty cell and 1 is a wall.
- ,
- , . and are row numbers, and are column numbers, and the top left cell is .
- The start cell and the exit cell are always empty.
Output
Print , 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 to get from the top left cell to the bottom right cell.