Depth First Search Algorithm In Python
(This question is followed up in more detail here: python-search-algorithm-from-implied-graphs) Suppose I have a function that takes an input ($x_i$) and then goes through a loop
Solution 1:
I think that just using an explicit stack for the current path and recursion is simpler:
defsearch(start_state, neighbors, goal):
path = [start_state]
classPathFound(RuntimeError):
passdefrsearch(x):
if goal(x):
raise PathFound
for y in neighbors(x):
path.append(y)
rsearch(y)
path.pop()
try:
rsearch(start_state)
except PathFound:
return path
returnNone# No path exists
Python has a low recursion limit but for a depth-first search this is normally not an issue (and it can be extended anyway by sys.setrecursionlimit
).
Solution 2:
classTree:
def__init__(self, value, children = None):
self.value = value
self.children = []
if children:
self.children = list(children)
defget_children(self):
returnlist(self.children)
defget_value(self):
return self.value
defhas_children(self):
if self.children:
returnTrue
node9 = Tree(9)
node5 = Tree(5, [node9])
node6 = Tree(6)
node3 = Tree(3, [node5, node6])
node7 = Tree(7)
node8 = Tree(8)
node4 = Tree(4, [node7, node8])
node2 = Tree(2)
node1 = Tree(1, [node2, node4, node3])
defiterate_child(child):
global level
print' ' * level * 2, child.get_value()
if child.has_children():
level += 1for s_child in child.get_children():
iterate_child(s_child)
level -= 1
level = 1print node1.get_value()
for child in node1.get_children():
iterate_child(child)
as you can see in the above image, I have iterated through the children of the node1 and recursively iterated over the children of the children node, first, and then processed the second child of the parent node.
Post a Comment for "Depth First Search Algorithm In Python"