Bessie's Dream#11162

Bessie's Dream

1 second
128 megabytes
Hard

After eating too much fruit in Farmer John's kitchen, Bessie the cow is having some very strange dreams! In her most recent dream, she is trapped in a maze in the shape of an n \times m grid of tiles. She starts on the top-left tile and wants to reach the bottom-right tile. When standing on a tile, she can potentially move to an adjacent tile in any of the four cardinal directions.

But wait! Each tile has a color, and each color has a different property! Bessie's head hurts just thinking about it:

Please help Bessie get from the top-left tile to the bottom-right tile in as few moves as possible.

Input

The first line contains two integers and m~(1 \le n, m \le 1000), representing the number of rows and columns in the maze.

The next lines each contain integers representing the maze:

  • The integer represents a red tile.

  • The integer represents a pink tile.

  • The integer represents an orange tile.

  • The integer represents a blue tile.

  • The integer represents a purple tile.

The top-left and bottom-right tiles will always contain .

Output

Print one integer representing the minimum number of moves Bessie must make to cross the maze, or if it is impossible to do so.

Examples

If you're confused about how purple tiles work, the example below illustrates their behavior.

In this example, Bessie walks one square down and two squares to the right, then slides one more square to the right. She then walks one square up, one square left, and one square down, sliding two more squares down. Finally, she walks one more square to the right. This takes a total of moves (DRRRULDDDR).

Example 1

Loading
Loading