DFS使用Python中的递归超过了DFS的最大递归深度



我已经写了一份Python代码,以使用Python中的递归DFS解决传教士和食人族问题。但是我一直遇到这个错误: RecursionError:最大递归深度超过

我不知道该怎么办,我一直坚持这么长时间。任何帮助或建议将为我挽救生命。谢谢。这是代码:

class State(object):
#left = 1
#right = 0 for boat
        def __init__(self, missionaries, cannibals, boat):
    self.missionaries = missionaries
    self.cannibals = cannibals
    self.boat = boat
#def __str__(self):
#    return "%s, %s %s %s" % (self.by_move, self.missionaries, self.cannibals, self.boat)
def is_valid(self):
    if self.missionaries < 0 or self.missionaries > 3:
        return False
    if self.cannibals < 0 or self.cannibals > 3:
        return False
    if self.boat > 1 or self.boat < 0:
        return False
    if self.missionaries < self.cannibals and self.missionaries > 0:
        return False
    # Check for the other side
    if self.missionaries > self.cannibals and self.missionaries < 3:
        return False
    return True
def is_goal(self):
    return self.missionaries == 0 and self.cannibals == 0 and self.boat == 0
def new_states(self):
    op = -1  # Subtract
    boat_move = "from left shore to right"
    if self.boat == 0:
        op = 1  # Add
        boat_move = "from right shore to left"
    for x in range(3):
        for y in range(3):
            by_move = "Move %s missionaries and %s cannibals %s" % (x, y, boat_move)
            new_state = State(self.missionaries + op * x, self.cannibals + op * y, self.boat + op * 1)
            if x + y >= 1 and x + y <= 2 and new_state.is_valid():
                yield new_state
class Node(object):
def __init__(self, parent, state, depth):
    self.parent = parent
    self.state = state
    self.depth = depth
def children(self):
    for state in self.state.new_states():
        yield Node(parent=self, state=state, depth=self.depth + 1)
def extract_solution(self):
    print
    "Extracting soln"
    solution = []
    node = self
    solution.append(node)
    while node.parent is not None:
        solution.append(node.parent)
        node = node.parent
    solution.reverse()
    return solution
def dfs(root,visited,sol = None):
if root in visited:
    return
if root is None:
    return
visited.append(root)
if root.state.is_goal():
    sol = root
    return
for child in root.children():
    if child not in visited:
        dfs(child,visited,sol)
def main():
    initial_state = State(3,3,1)
    root = Node(parent = None, state = initial_state,depth = 0)
    visited = []
    sol = Node(parent = None, state = initial_state,depth = 0)
    dfs(root,visited,sol)
    ans = sol.extract_solution()
    print(ans)

if __name__ == '__main__':
    main()

有两个问题:

1:您的列表"访问"并未正确跟踪所有状态。可以通过使访问的全局变量(通过将其放在最终解决方案中完成的DEF MAIM((前面(来轻松修复这一点

2:该程序正在搜索任何可能不会有帮助的可能性(例如:来回来回(,这个

if root in visited:
    return
if root is None:
    return

没有解决这个问题,因为它永远不会是相同的根对象(即使root.state.sprisearies,Cannibals和Boat是相同的值(,所以我使用字典对象更改了此对象:

if root is None:
    return
state = str(root.state.missionaries) + ',' + str(root.state.cannibals) + ',' + str(root.state.boat)
if state in routes:
    if routes[state] < root.depth:
        return
    else:
        routes[state] = root.depth
else:
    routes[state] = root.depth
visited.append(root)

这会导致以下代码(它返回答案,我不确定这是正确的代码,因为我不知道传教士和食人族问题(

class State(object):
#left = 1
#right = 0 for boat
    def __init__(self, missionaries, cannibals, boat):
        self.missionaries = missionaries
        self.cannibals = cannibals
        self.boat = boat
    #def __str__(self):
    #    return "%s, %s %s %s" % (self.by_move, self.missionaries, self.cannibals, self.boat)
    def is_valid(self):
        if self.missionaries < 0 or self.missionaries > 3:
            return False
        if self.cannibals < 0 or self.cannibals > 3:
            return False
        if self.boat > 1 or self.boat < 0:
            return False
        if self.missionaries < self.cannibals and self.missionaries > 0:
            return False
        # Check for the other side
        if self.missionaries > self.cannibals and self.missionaries < 3:
            return False
        return True
    def is_goal(self):
        return self.missionaries == 0 and self.cannibals == 0 and self.boat == 0
    def new_states(self):
        op = -1  # Subtract
        boat_move = "from left shore to right"
        if self.boat == 0:
            op = 1  # Add
            boat_move = "from right shore to left"
        for x in range(3):
            for y in range(3):
                by_move = "Move %s missionaries and %s cannibals %s" % (x, y, boat_move)
                new_state = State(self.missionaries + op * x, self.cannibals + op * y, self.boat + op * 1)
                if x + y >= 1 and x + y <= 2 and new_state.is_valid():
                    yield new_state
class Node(object):
    def __init__(self, parent, state, depth):
        self.parent = parent
        self.state = state
        self.depth = depth
    def children(self):
        for state in self.state.new_states():
            yield Node(parent=self, state=state, depth=self.depth + 1)
    def extract_solution(self):
        print "Extracting soln"
        solution = []
        node = self
        solution.append(node)
        while node.parent is not None:
            solution.append(node.parent)
            node = node.parent
        solution.reverse()
        return solution
def dfs(root,sol = None):
    if root is None:
        return
    state = str(root.state.missionaries) + ',' + str(root.state.cannibals) + ',' + str(root.state.boat)
    if state in routes:
        if routes[state] < root.depth:
            return
        else:
            routes[state] = root.depth
    else:
        routes[state] = root.depth
    visited.append(root)
    if root.state.is_goal():
        sol = root
        return
    for child in root.children():
        if child not in visited:
            dfs(child,sol)
visited = []
routes = {}
def main():
    initial_state = State(3,3,1)
    root = Node(parent = None, state = initial_state,depth = 0)
    sol = Node(parent = None, state = initial_state,depth = 0)
    dfs(root,sol)
    ans = sol.extract_solution()
    print(ans)

if __name__ == '__main__':
    main()

ps。正如@pm 2ring所说,下一次:在提出问题时请修复您的缩进,这使得阅读您的代码更容易理解。您可以通过选择所有代码,将选项卡添加到所选的所有行,然后复制。在粘贴之前,请确保有一个空线。:(

最新更新