All problems

Problem 937

Minimum Cost to Make at Least One Valid Path in a Grid

Hard · 30 pts · Matrix, Graph, Breadth-First Search, Shortest Path

Problem

Every cell of a grid holds a sign pointing to a neighbour: 1 = right, 2 = left, 3 = down, 4 = up. Starting at the top-left cell, you follow the signs. You may change the sign of any cell for a cost of 1 (each cell at most once). Find the minimum total cost to make a path from the top-left to the bottom-right cell. Following a sign costs 0 and moving in another direction costs 1, so a 0-1 BFS with a deque finds the cheapest path.

Input

The first line contains R and C. Each of the next R lines contains C signs (1 to 4).

Output

Print the minimum cost.

Constraints

1 <= R, C <= 100; every sign is 1, 2, 3 or 4

Example input

4 4
1 1 1 1
2 2 2 2
1 1 1 1
2 2 2 2

Example output

3

Explanation

In 1 1 1 1 / 2 2 2 2 / 1 1 1 1 / 2 2 2 2, follow the first row right, change one sign to go down, follow the third row, and change one more sign. The minimum cost is 3, since each move down needs a change.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Jump Game IV Next: Shortest Path to Get All Keys