call(back)
Algorithms & Data StructuresmediumSign in to star problems

Wiki Page Links I

You are given getLinkedPages(uri), which fetches a wiki page and returns the URIs it links to. Return the fewest clicks needed to get from start to target, or -1 if target cannot be reached. Going from a page to itself takes 0 clicks.

// A -> B, A -> C, B -> D, C -> D
fewestClicks("A", "D", getLinkedPages)  ->  2
fewestClicks("D", "A", getLinkedPages)  ->  -1

Fetching is expensive: the harness fails a run that fetches the same page twice. The harness's fetcher returns an empty list for pages it knows nothing about.

Hints

Hint 1

Breadth-first search over an implicit graph: the queue holds pages, and expanding a page is one fetch. Visiting in BFS order means the first time you see the target is along a shortest path.

Hint 2

Record a page as seen when it is first discovered — before it is fetched — so two parents cannot both enqueue it.

Asked at