I am trying a number of search algorithms for an generalized AI problem, one of which is depth-first-search. I have converted breadth-first-search, greedy, and A* searches from their natural recursive form into an iterative one, but am having a bit more trouble doing it cleanly
with depth-first-search (although it's not beyond my abilities, I'm not sure the most pythonic way to do so, hence the question).
I am running into trouble with CPython's 1000 recursive-call limit for even some medium-sized problems. Successor states are generated lazily (_generate_states
is a generator, not a list), and the path from the initial state is required.
What is the most pythonic way to move from using the call stack to an explicit stack? How much information should be stored in the stack? When backtracking (when no states return a non-empty list), what is the best way to pop dead information from the front of the stack?
def dfs(initial, closed_set, goal, capacity):
if initial == goal:
return [initial]
for state in _generate_states(initial, capacity):
if state not in closed_set:
result = dfs(state, [initial] + closed_set, goal, capacity)
if result:
return [state] + result
return []