One Letter at a Time
You want to turn the word start into the word goal. One step changes a single letter, and the word you get must be on the list words. The word start itself does not have to be on the list.
Return the fewest steps, or -1 if goal cannot be reached. If start equals goal, the answer is 0.
Example 1
start "cold"
goal "warm"
words ["cord","card","ward","warm","word","worm"]
returns 4
cold, cord, card, ward, warm: four steps. The way over word and worm is just as long.
Example 2
start "aa"
goal "bb"
words ["bb"]
returns -1
Both letters differ, and the only word on the list is the goal itself: no single change leads anywhere.
Example 3
start "aa"
goal "aa"
words ["zz"]
returns 0
Nothing has to change.
Constraints
1 <= len(words) <= 30, all differentstart,goaland every word have the same length, 1 to 5 lowercase letters
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Graphs problems
- Order of a Strange AlphabetHard
- Second Best TripHard
- Tour Every RoomHard
- Turn the SignpostsHard
- Use Every TicketHard
- Arrows In and OutBeginner
- Build the Neighbor ListsBeginner
- Can You Walk ItBeginner