Search~15 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-1971dfs
A search crawler follows links between n web pages, numbered from 0. A link goes one way, from the page that holds it to the page it points to.
Every page has a sensitivity level from 1 to 10. A crawler with clearance c may only visit pages whose level is at most c. It may not visit any other page, even to pass through.
Write can_reach(n, links, levels, source, target, clearance).
links[i] is [a, b]: page a links to page b. The same link may appear twice.levels[i] is the level of page i.source and follows links, visiting only pages with level at most clearance. The source counts as visited.true when the crawler can visit target, and false otherwise.Input: n = 6, links = [[0,1],[0,3],[1,2],[3,4],[4,2],[2,5]], levels = [1,3,1,2,1,1], source = 0, target = 5, clearance = 2
Output: truePage 1 has level 3, which is above the clearance, so the crawler never enters it. A stack holds the pages still to read.
| Step | Page taken | Pages pushed | Pages refused |
|---|---|---|---|
| 1 | 0 | 3 | 1 (level 3) |
| 2 | 3 | 4 | |
| 3 | 4 | 2 | |
| 4 | 2 | 5 | |
| 5 | 5 |
Page 5 is the target, so the answer is true.
Input: n = 6, links = [[0,1],[0,3],[1,2],[3,4],[4,2],[2,5]], levels = [1,3,1,2,1,1], source = 0, target = 5, clearance = 1
Output: falseWith clearance 1, page 3 (level 2) is refused as well, so the crawler is stuck at page 0.
Input: n = 1, links = [], levels = [5], source = 0, target = 0, clearance = 3
Output: falseThe source is also the target, but its level is above the clearance, so the crawler cannot even start.
1 ≤ n ≤ 100,000, and levels has n entries from 1 to 100 ≤ links.length ≤ 300,000, and each link joins two pages from 0 to n - 10 ≤ source, target < n and 1 ≤ clearance ≤ 10Repeating a pass over all 300,000 links until nothing new is reached can need one pass per page on a long chain. That is up to 100,000 × 300,000 = 3 × 10^10 steps. A walk that visits each page once and reads each link once costs O(n + m), about 400,000 steps.