Arrow Grid Detour
You are given a grid with r rows and c columns. Every cell holds an arrow: U (up), D (down),
L (left) or R (right).
You start in the top-left cell (row 1, column 1) and want to reach the bottom-right cell (row r,
column c). In one move you go from your current cell to one of its up to four side-adjacent
cells. You can never leave the grid.
- A move in the direction of the arrow in your current cell is free.
- A move in any other direction costs 1. Think of it as repainting that cell's arrow before you follow it.
The cost of a route is the sum of the costs of its moves. Cells may be visited any number of times, and each move is paid for separately. An arrow that points off the grid can never be followed for free.
Find the minimum cost of a route from the top-left cell to the bottom-right cell.
Input
The first line contains two integers r and c (1 ≤ r, c and r·c ≤ 10^6).
Each of the next r lines contains a string of exactly c characters, each of them U, D, L
or R: the arrows of one row, from left to right.
Output
Print one integer: the minimum cost.
Notes
In the first example the arrows let you walk for free from (1,1) to (1,3), but no further: the arrow
there points back to the left. Paying 1 to step down to (2,3) puts you on a D, which takes you to
the goal for free. Every free walk from the start stays in the first row, so the answer is 1.
In the second example the route (1,1) → (1,2) → (1,3) → (2,3) → (2,2) → (3,2) → (3,3) → (3,4) follows the arrow in every cell, so it costs nothing, even though it steps left once.
If r = c = 1, you are already at the goal and the answer is 0.