我一直在尝试不同的方式来实现深度优先搜索。我找到了一些工作方法,但它们涉及一些相当繁琐的字典工作。我使用列表开发了一个新想法,但是此实现返回的操作与所需的结果不匹配。我会尽量清楚地注释代码:
start = problem.getStartState() ## returns an (x, y) tuple
children = problem.getSuccessors(start) ##returns the children of a parent node in ((start
state), action, cost) format.
stack = Stack() ##creates a Stack (LIFO) data structure
visited = [] ##list of visited nodes
visited.append(start)
for child in children:
stack.push((child, [], [], 0)) ##push children to fringe in the format of (child,
while stack: ##path taken, actions taken, cost)
parent = stack.pop()
node = parent[0]
if parent[0] in visited: continue
visited.append(parent[0])
path = parent[1] + [node[0]] ##assigns previous path/actions/cost to new
actions = parent[2] + [node[1]] ##node, creating a cumulative, ordered list of
print actions ##the path/actions and a cumulative cost
cost = parent[3] + node[2]
if problem.isGoalState(node[0]):
print parent[2]
return parent[2] ## returns list of actions
children = problem.getSuccessors(node[0])
if children != []:
for child in children:
stack.push((child, path, actions, cost)) ##assigns cumulative lists to child
任何人都看到我的问题在这个实现中可能出在哪里?顺便说一句,我知道 DFS 在大多数情况下是一种低效的算法。但是一旦我正确地实现了这个实现,它应该能够通过简单地更改存储父节点子节点的数据结构来跨越其他搜索算法。