problems / 152

Arrow Grid Detour

medium queue bfs graphs shortest-paths 2500 ms · 256 MB

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.

Example 1

Input

3 3
RRL
UUD
LLU

Output

1

Example 2

Input

3 4
RRDL
UDLU
RRRU

Output

0

Hints · reveal one at a time if you're stuck

Hint 1

Treat each cell as a node with an edge to each neighbour. Following the arrow costs 0 and any other move costs 1. Which shortest-path method suits edge weights that are only 0 or 1, and avoids the cost of a general priority queue?

Hint 2

Use a double-ended queue: a free move goes to the front and a paid move goes to the back, so cells are processed in cost order. Be careful with when you mark a cell as finished, since a cell first reached by a paid move may later be reachable for free.

report an issue Prefer your own editor? sooks prep 152 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.