def populate_kids(self, arr, used_Indices):
for a in self.children:
a.get_all_jumps(arr, used_Indices)
for a in self.children:
for b in a.children:
b.get_all_jumps(arr, used_Indices)
for a in self.children:
for b in a.children:
for c in b.children:
c.get_all_jumps(arr, used_Indices)
for a in self.children:
for b in a.children:
for c in b.children:
for d in c.children:
d.get_all_jumps(arr, used_Indices)
How do I make this automatically
I tried recursion it doesn't seem to work
This looks like a BFS (breadth-first-search), so something along these lines might work:
def populate_kids(self, arr, used_Indices):
queue = self.children
while queue:
next_queue = []
for a in queue:
a.get_all_jumps(arr, used_Indices)
if a.children:
next_queue.extend(a.children)
queue = next_queue
The basic idea is that as you process the queue, you add the next level of items to search to the queue for the next iteration. Eventually you reach the point where there are no more levels, and the search ends.
For a DFS (depth-first search), recursion is easier (I'm assuming the objects in self.children
have the same type as self
):
def populate_kids(self, arr, used_Indices):
for a in self.children:
a.get_all_jumps(arr, used_Indices)
a.populate_kids(arr, used_Indices)
but the order of traversal will be different (you'll recurse all the way down to the deepest level before finishing the loop at the current level).