Google questions

Shortest Paths in a Graph

GoogleOnsiteHard

A road map is an undirected, unweighted graph with n nodes numbered 0 to n - 1. edges[k] = [u, v] joins two different nodes, and no pair is listed twice. The graph may be disconnected. PathFinder(n, edges) is built once and then answers queries about it. The graph never changes after construction.

Part 1: Shortest distance

Implement shortest_distance(start, target), which returns the smallest number of edges on a path from start to target, or -1 if there is no such path. A node is at distance 0 from itself.

  1. Example 1
    init
    [7,[[0,1],[1,2],[2,5],[0,3],[3,4],[4,5],[1,4]]]
    operations
    [["shortest_distance",[0,5]],["shortest_distance",[0,0]],["shortest_distance",[2,3]],["shortest_distance",[0,6]],["shortest_distance",[6,6]],["shortest_distance",[5,0]]]
    Output
    [3,0,3,-1,0,3]

    Why: Node 0 reaches node 5 in 3 edges (0-1-2-5, 0-3-4-5 and 0-1-4-5 all have 3). A node is at distance 0 from itself. Node 6 has no edges, so it is unreachable and the answer is -1.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(edges) <= 2 * 10^5
  • 0 <= start, target < n
  • 1 <= len(operations) <= 100
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question