Editor

One-Way Streets

#61 · Graphs · Intermediate · 60 XP · about 10 min

A small town has only one-way streets. The dictionary streets maps each place to the list of places you can drive to directly from it. Write can_reach(streets, start, goal) that returns True if you can drive from start to goal following the streets in their direction, and False otherwise.

You are already at start, so can_reach(streets, x, x) is always True. A place that appears only inside lists has no streets leaving it.

Examples

streets = {
    'home': ['bakery', 'park'],
    'bakery': ['school'],
    'park': ['home'],
    'school': [],
}
can_reach(streets, 'home', 'school')  # returns True
can_reach(streets, 'school', 'home')  # returns False
can_reach(streets, 'park', 'school')  # returns True

From the park you drive home, then to the bakery, then to the school. No street leaves the school, so you can never get back from there.

Constraints

  • Up to 1,000 places and 5,000 streets.
  • Streets can form loops, such as home to the park and back again.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.