Search~30 min2s · 256 MBtarget O(n + m) time, O(n + m) spacebfs
You work on a search engine's crawler. A site has n pages, numbered 0 to n - 1, joined by one-way links. Following a link to a page that is already cached costs nothing. Following a link to a page that is not cached uses one paid fetch.
Each link is marked as free or paid in advance. The crawler wants to get from a start page to a target page with as few paid fetches as possible. It can follow as many free links as it likes.
Your team lead asks: "What is the fewest paid fetches needed to reach the target page?" The site can have 100,000 pages and 200,000 links.
Write fewest_paid_hops(n, links, source, target).
links[k] = [a, b, paid] is a one-way link from page a to page b. When paid is 0 the link is free, and when paid is 1 it costs one paid fetch. Links can repeat.source to target, where each link starts where the previous one ended.source = target the answer is 0. Return -1 when target cannot be reached.Input: n = 6, links = [[0, 1, 0], [1, 2, 1], [0, 3, 1], [3, 2, 0], [2, 4, 0], [4, 5, 1]], source = 0, target = 5
Output: 2Two routes lead to page 5: 0 → 1 → 2 → 4 → 5 and 0 → 3 → 2 → 4 → 5. Each uses 2 paid links, because the link 4 → 5 is paid and one earlier link is paid. The fewest paid links to each page, in the order the pages are settled:
| Page | Fewest paid links |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 3 | 1 |
| 2 | 1 |
| 4 | 1 |
| 5 | 2 |
Page 5 needs 2 paid links.
Input: n = 3, links = [[1, 0, 0], [1, 2, 1]], source = 0, target = 2
Output: -1No link leaves page 0, so page 2 cannot be reached.
Input: n = 2, links = [[0, 1, 1]], source = 1, target = 1
Output: 0The crawler is already at the target page, so it needs no fetch.
1 ≤ n ≤ 100,0000 ≤ len(links) ≤ 200,0000 ≤ links[k][0], links[k][1] < n, and links[k][2] is 0 or 10 ≤ source, target < nRepeating a pass over all links until nothing improves can take up to 100,000 passes of 200,000 links, which is 20 billion steps. Costs of only 0 and 1 are special. A heap is more than we need, because a double-ended queue keeps the pages in order of their cost in constant time.