Skip to the code
cf.
+10 XP

#460 Cheapest Route Between Two Screens

easy

A mobile app's navigation map has n screens numbered 0 to n - 1. Each moves[i] = [from, to, cost] means you can go from screen from to screen to, and cost is how many taps that transition takes.

Write cheapestRoute(n, moves, from, to) that returns the fewest total taps to get from screen from to screen to, or -1 if it can't be done. If from === to, the answer is 0.

Example 1

Input: n = 4, moves = [[0,1,5],[0,2,1],[2,1,1],[1,3,1]], from = 0, to = 3
Output: 3

Going 0 → 2 → 1 → 3 costs 1 + 1 + 1 = 3, cheaper than 0 → 1 → 3 at 6.

Example 2

Input: n = 3, moves = [[0,1,2]], from = 0, to = 2
Output: -1

No move leads to screen 2.

Constraints

  • 1 <= n <= 1000
  • 0 <= moves.length <= 10000
  • 1 <= cost <= 100
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).