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

Function create_state_space_tree

backtracking/all_permutations.py:16–74  ·  view source on GitHub ↗

Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly len(sequence) - index children. It terminates when it reaches the end of the given sequence. :param sequence: The input sequence for which permutations are generated. :param

(
    sequence: list[int | str],
    current_sequence: list[int | str],
    index: int,
    index_used: list[int],
)

Source from the content-addressed store, hash-verified

14
15
16def create_state_space_tree(
17 sequence: list[int | str],
18 current_sequence: list[int | str],
19 index: int,
20 index_used: list[int],
21) -> None:
22 """
23 Creates a state space tree to iterate through each branch using DFS.
24 We know that each state has exactly len(sequence) - index children.
25 It terminates when it reaches the end of the given sequence.
26
27 :param sequence: The input sequence for which permutations are generated.
28 :param current_sequence: The current permutation being built.
29 :param index: The current index in the sequence.
30 :param index_used: list to track which elements are used in permutation.
31
32 Example 1:
33 >>> sequence = [1, 2, 3]
34 >>> current_sequence = []
35 >>> index_used = [False, False, False]
36 >>> create_state_space_tree(sequence, current_sequence, 0, index_used)
37 [1, 2, 3]
38 [1, 3, 2]
39 [2, 1, 3]
40 [2, 3, 1]
41 [3, 1, 2]
42 [3, 2, 1]
43
44 Example 2:
45 >>> sequence = ["A", "B", "C"]
46 >>> current_sequence = []
47 >>> index_used = [False, False, False]
48 >>> create_state_space_tree(sequence, current_sequence, 0, index_used)
49 ['A', 'B', 'C']
50 ['A', 'C', 'B']
51 ['B', 'A', 'C']
52 ['B', 'C', 'A']
53 ['C', 'A', 'B']
54 ['C', 'B', 'A']
55
56 Example 3:
57 >>> sequence = [1]
58 >>> current_sequence = []
59 >>> index_used = [False]
60 >>> create_state_space_tree(sequence, current_sequence, 0, index_used)
61 [1]
62 """
63
64 if index == len(sequence):
65 print(current_sequence)
66 return
67
68 for i in range(len(sequence)):
69 if not index_used[i]:
70 current_sequence.append(sequence[i])
71 index_used[i] = True
72 create_state_space_tree(sequence, current_sequence, index + 1, index_used)
73 current_sequence.pop()

Callers 1

Calls 2

appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected