Skip to the code
cf.
+10 XP

#408 Fewest Clicks Between Pages

easy

A docs site has n pages numbered 0 to n - 1. Each pair links[i] = [a, b] means page a has a link to page b. Links only work in that direction.

Write fewestClicks(n, links, from, to) that returns the fewest link clicks needed to get from page from to page to, or -1 if to can't be reached. If from === to, the answer is 0.

Example 1

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

One shortest route is 0 → 1 → 2 → 4: three clicks.

Example 2

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

Page 0 links to 1, but nothing links on to page 2.

Constraints

  • 1 <= n <= 10000
  • 0 <= links.length <= 50000
  • 0 <= a, b, from, to < n
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).