Why it works
- BFS goes level by level and steps counts the words up to the current level, so the first time the end word comes up, steps + 1 is the shortest ladder.
- A word is taken out of the set the moment it is queued: a second word of the same level that leads to it finds it gone, so nothing is queued twice and no visited set is needed.
- If the end word is not in the list, no ladder can end there, so the answer is 0 before any search.
Complexity
Time O(n · 26 · L²) for n words of length L: each word is queued once and tries 26 letters in each of its L places, and making and looking up each new word takes O(L). Memory O(n) for the set and the queue.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗