30 · Advanced Graphs: Euler Paths, Bridges & SCCs

#815 Bus Routes

Hardsolve on LeetCode ↗

frequently reported atUberAmazonGoogle

the problem

In plain words

Each routes[i] lists the stops of bus i, which drives that loop forever. You stand at stop source and are not on any bus. You can move between stops only by riding buses, and you may change buses at any stop they share. Return the smallest number of buses you must board to reach stop target, or -1 if it can't be done.

in routes = [[1,2,7],[3,6,7]], source = 1, target = 6

out 2

Ride bus 0 from stop 1 to stop 7, change to bus 1, ride to stop 6.

in routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12

out -1

Stop 15 is on buses 1 and 3, which only reach stops 4, 5, 15 and 19. None of them leads to stop 12.

  • 1 ≤ routes.length ≤ 500
  • 1 ≤ routes[i].length ≤ 10⁵; a route lists each stop once
  • The total number of stop entries is at most 10⁵
  • 0 ≤ routes[i][j], source, target < 10⁶

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #127
      Word Ladder
      Hardin Graphs
    2. #909
      Snakes and Ladders
      Mediumin Graphs
    3. #787
      Cheapest Flights Within K Stops
      Mediumin Shortest Paths