MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / backtrack

Function backtrack

backtracking/word_ladder.py:15–65  ·  view source on GitHub ↗

Helper function to perform backtracking to find the transformation from the current_word to the end_word. Parameters: current_word (str): The current word in the transformation sequence. path (list[str]): The list of transformations from begin_word to current_word. end_word

(
    current_word: str, path: list[str], end_word: str, word_set: set[str]
)

Source from the content-addressed store, hash-verified

13
14
15def backtrack(
16 current_word: str, path: list[str], end_word: str, word_set: set[str]
17) -> list[str]:
18 """
19 Helper function to perform backtracking to find the transformation
20 from the current_word to the end_word.
21
22 Parameters:
23 current_word (str): The current word in the transformation sequence.
24 path (list[str]): The list of transformations from begin_word to current_word.
25 end_word (str): The target word for transformation.
26 word_set (set[str]): The set of valid words for transformation.
27
28 Returns:
29 list[str]: The list of transformations from begin_word to end_word.
30 Returns an empty list if there is no valid
31 transformation from current_word to end_word.
32
33 Example:
34 >>> backtrack("hit", ["hit"], "cog", {"hot", "dot", "dog", "lot", "log", "cog"})
35 ['hit', 'hot', 'dot', 'lot', 'log', 'cog']
36
37 >>> backtrack("hit", ["hit"], "cog", {"hot", "dot", "dog", "lot", "log"})
38 []
39
40 >>> backtrack("lead", ["lead"], "gold", {"load", "goad", "gold", "lead", "lord"})
41 ['lead', 'lead', 'load', 'goad', 'gold']
42
43 >>> backtrack("game", ["game"], "code", {"came", "cage", "code", "cade", "gave"})
44 ['game', 'came', 'cade', 'code']
45 """
46
47 # Base case: If the current word is the end word, return the path
48 if current_word == end_word:
49 return path
50
51 # Try all possible single-letter transformations
52 for i in range(len(current_word)):
53 for c in string.ascii_lowercase: # Try changing each letter
54 transformed_word = current_word[:i] + c + current_word[i + 1 :]
55 if transformed_word in word_set:
56 word_set.remove(transformed_word)
57 # Recur with the new word added to the path
58 result = backtrack(
59 transformed_word, [*path, transformed_word], end_word, word_set
60 )
61 if result: # valid transformation found
62 return result
63 word_set.add(transformed_word) # backtrack
64
65 return [] # No valid transformation found
66
67
68def word_ladder(begin_word: str, end_word: str, word_set: set[str]) -> list[str]:

Callers 1

word_ladderFunction · 0.70

Calls 2

removeMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected