Skip to the code
cf.
+50 XP

#438 Follow the Arrows With Fewest Changes

hard

A puzzle game shows a grid of arrows as strings: "R" points right, "L" left, "U" up, and "D" down. A token starts in the top-left cell and moves one cell in the direction its current cell's arrow points. You may change the arrow of any cell before the token moves, and each change costs 1.

Write fewestChanges(arrows) that returns the smallest total cost to make the token reach the bottom-right cell. An arrow pointing off the grid is allowed, but the token can't follow it.

Example 1

Input: arrows = ["RRD","LLL","RRR"]
Output: 1

Following the arrows goes right, right, down, left, left, and then off the left edge. Changing (1, 2) from L to D sends the token straight to the bottom-right.

Example 2

Input: arrows = ["R"]
Output: 0

The token already starts on the bottom-right cell.

Constraints

  • 1 <= arrows.length, arrows[i].length <= 100
  • Each cell is "R", "L", "U", or "D".
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).