我正在尝试在 Python 中进行深度优先搜索,但它不起作用。
基本上我们有一个钉子纸牌板:
[1,1,1,1,1,0,1,1,1,1]
1 代表挂钩,0 代表空位。您必须一次将一个钉子向后或向前移动两个槽位到一个空位。如果您在此过程中跳过另一个挂钩,它将成为一个空槽。你这样做直到剩下一个钉子。所以基本上,一个游戏是这样的:
[1, 1, 1, 1, 1, 0, 1, 1, 1, 1]
[1, 1, 1, 0, 0, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 0, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 1, 0, 0, 1, 1, 1]
[1, 0, 0, 0, 0, 1, 0, 1, 1, 1]
[1, 0, 0, 0, 0, 1, 1, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1, 0, 1] #etc until only 1 peg left
这是我所拥有的:
class MiniPeg():
def start(self):
''' returns the starting board '''
board = [1,1,1,1,1,0,1,1,1,1]
return board
def goal(self, node):
pegs = 0
for pos in node:
if pos == 1:
pegs += 1
return (pegs == 1) # returns True if there is only 1 peg
def succ(self, node):
pos = 0
for peg in node:
if peg == 1:
if pos < (len(node) - 2): # try to go forward
if node[pos+2] == 0 and node[pos+1] == 1:
return create_new_node(node, pos, pos+2)
if pos > 2: # try to go backwards
if node[pos-2] == 0 and node[pos-1] == 1:
return create_new_node(node, pos, pos-2)
pos += 1
def create_new_node(node, fr, to):
node[fr] = 0
node[to] = 1
if fr > to:
node[fr-1] = 0
else:
node[fr+1] = 0
return node
if __name__ == "__main__":
s = MiniPeg()
b = s.start()
while not s.goal(b):
print b
b = s.succ(b)
所以,现在我的问题:
- 这是进行深度优先搜索的正确方法吗?
- 我的算法不行!!!它卡住了。在问这里之前,我已经为此苦苦挣扎了几天,所以请帮忙。
- 看起来我没有关注 DRY,有什么建议吗?
- 天哪,帮帮我?