DFS和BFS的8-puzzle解算器

时间:2017-02-06 01:54:37

标签: python

import Queue
import sys
sys.getrecursionlimit()
sys.setrecursionlimit(200000)

class State:
def __init__(self, board, space, prev):
    self.board = board
    self.space = space
    self.prev = prev

adjacent = (
(3, 1),       # 0
(4, 0, 2),    # 1
(5, 1),       # 2
(0, 6, 4),    # 3
(1, 7, 3, 5), # 4
(2, 8, 4),    # 5
(3, 7),       # 6
(4, 6, 8),    # 7
(5, 7)        # 8)

GOAL = [0,1, 2, 3, 4, 5, 6, 7, 8]

我想解决8-puzzle,以便我如上所述制作BFS(广度优先搜索)如下:

def bf_search(start):
    q = Queue.Queue()
    q.put(State(start, start.index(0), None))
    table = {}
    table[tuple(start)] = True

    while not q == []:
        a = q.get()

        for x in adjacent[a.space]:
        b = a.board[:]
        b[a.space] = b[x]
        b[x] = 0
        key = tuple(b)

        if key in table: continue
        c = State(b, x, a)

        if b == GOAL:
            print_answer(c)
            return

        q.put(c)
        table[key] = True


def print_answer(x):
    if x is not None:
        print_answer(x.prev)
        print(x.board)

当我运行它时,它运行良好没有任何问题。 比如

bf_search([1,2,5,3,4,0,6,7,8])
[1, 2, 5, 3, 4, 0, 6, 7, 8]
[1, 2, 0, 3, 4, 5, 6, 7, 8]
[1, 0, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8]

但如果我想将它应用于DFS(深度优先搜索),我会遇到问题。

我只是改变

def bf_search(start):
    q = Queue.Queue()

def df_search(start):
    q = Queue.LifoQueue()

用于更改队列(FIFO)到堆栈(LIFO)。

但效果不佳。即使它可以找到目标,目标和目标(-1状态)

df_search([1,2,5,3,4,0,6,7,8])
[3, 1, 2, 0, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8]

在这种情况下(起始点为[1,2,5,3,4,0,6,7,8]),DFS的解决方案(路径)必须与BFS相同。

我需要你的建议来解决它。

0 个答案:

没有答案