Coding
You receive the following inputs:
start wordtarget wordDecide whether a legal sequence of word changes can link the first word to the second.
A transition must go from the current word to a same-length word. Typically, the initial version permits changing one character, followed by a variant that permits changing either one or two characters.
This can be viewed as a Word Ladder graph:
start and targetUse these assumptions:
start and target contain lowercase lettersstart is not required to appear in the dictionarytarget remains an allowed final destination even when absent from the dictionaryImplement:
def solve(start: str, target: str, words: list[str], part: int) -> bool:
...
Produce True when a transformation chain exists from start to target with these properties:
target is allowed as the last word even when the dictionary does not contain itstart = "cold"
target = "warm"
words = ["cord", "card", "ward"]
solve(start, target, words, 1) # True
A possible sequence is:
cold -> cord -> card -> ward -> warm
Each neighboring pair differs at exactly one position, and only the endpoint warm is allowed to be outside the dictionary.
Expand the movement condition as follows:
Implement:
def solve(start: str, target: str, words: list[str], part: int) -> bool:
...
start = "bake"
target = "torn"
words = ["bore", "tone"]
solve(start, target, words, 2) # True
One valid chain is:
bake -> bore -> tone -> torn
For example, this transition is permitted:
bore -> tone
It changes two character locations.
Instead of returning only a boolean, return a shortest legal chain.
Implement:
def solve(start: str, target: str, words: list[str], part: int) -> list[str]:
...
Return:
start and target[] when no valid sequence can be formedstart = "bake"
target = "torn"
words = ["bore", "tone"]
solve(start, target, words, 3)
# ["bake", "bore", "torn"]
This shorter route is legal because both bake -> bore and bore -> torn modify two positions, which this version permits.