Can the Van Get There?

Easy · Graphs, BFS & DFS · about 12 min

A delivery van drives in a town with n junctions numbered 0 to n - 1. Each [a, b] in roads is a two-way road between junctions a and b.

Return True / true if the van can drive from junction start to junction goal using any number of roads, otherwise False / false. If start equals goal, the van is already there, so the answer is true.

  • 1 <= n, and start and goal are valid junctions.

Example:

can_drive_between(4, [[0, 1], [1, 2], [2, 3]], 0, 3) → True

Hints

  • Build a list of neighbours for every junction, adding each road both ways.
  • Start a search from the start junction and mark every junction you visit.
  • Answer true the moment you visit the goal, and false when the search runs out of junctions.

Learn the pattern first: the Graphs, BFS & DFS lesson.

More Graphs, BFS & DFS problems