迭代深度限制搜索返回次优路径 - Python

时间:2014-01-25 22:01:18

标签: python depth-first-search graph-traversal

与标题一样,我的迭代深度限制搜索返回次优路径。

这不是作业;只关心IDLS如何与BFS相比起作用

显然我有一些东西可以忽略,但我的代码没有返回最佳路径,并且当设置限制(没有迭代)运行时,或者恰好高于最佳值时,它不返回任何路径。

节点包含:state,pathCost和solution(路径)

以下是代码:

def depthLimitedSearch(problem, limit = 999999):
"""
Search the deepest nodes in the search tree first, up to limit depth. 
"""

  node = Node(problem.getStartState())
  if problem.isGoalState(node.state):
    return node.solution

  frontier = util.Stack()
  frontier.push(node);
  explored = set([node.state]);



  while not frontier.isEmpty():
    node = frontier.pop()
    explored.add(node.state)

    for child in node.createChildren(problem):
      if child.pathCost <= limit:
        if (child.state not in explored):
          if (child not in frontier.list):
            if problem.isGoalState(child.state):
              return child.solution
            frontier.push(child)

  return []

def iterateDLS(problem, limit = 999999, inc = 1):
''' iterate DLS starting from limit and rising in inc increments'''
  result = []
  while result == []:
    result = depthLimitedSearch(problem, limit)
    limit += inc
  return result
''' testing for fixed limit'''
##  limit = 31
##  result = depthLimitedSearch(problem, limit)

0 个答案:

没有答案