def __init__(self, board): self.pq = MinPQ() self.goal = None self.pq.insert(self._Node(board)) while True: node = self.pq.delMin() if node.board.goal(): self.goal = node break for neighbor in node.board.neighbors(): n = self._Node(neighbor, node.moves + 1, node) if not node.prev is None: if neighbor != node.board: self.pq.insert(n) else: self.pq.insert(n)
class Solver(object): class _Node(object): def __init__(self, board, moves = 0, prev = None): self.board = board self.moves = moves self.prev = prev def priority(self): return self.board.manhattan() + self.moves def __cmp__(self, other): return self.priority() - other.priority() def __init__(self, board): self.pq = MinPQ() self.goal = None self.pq.insert(self._Node(board)) while True: node = self.pq.delMin() if node.board.goal(): self.goal = node break for neighbor in node.board.neighbors(): n = self._Node(neighbor, node.moves + 1, node) if not node.prev is None: if neighbor != node.board: self.pq.insert(n) else: self.pq.insert(n) def moves(self): return self.goal.moves if not self.goal is None else -1 def solution(self): stck = Stack() node = self.goal while not node is None: stck.push(node.board) node = node.prev return stck
class Solver(object): class _Node(object): def __init__(self, board, moves=0, prev=None): self.board = board self.moves = moves self.prev = prev def priority(self): return self.board.manhattan() + self.moves def __cmp__(self, other): return self.priority() - other.priority() def __init__(self, board): self.pq = MinPQ() self.goal = None self.pq.insert(self._Node(board)) while True: node = self.pq.delMin() if node.board.goal(): self.goal = node break for neighbor in node.board.neighbors(): n = self._Node(neighbor, node.moves + 1, node) if not node.prev is None: if neighbor != node.board: self.pq.insert(n) else: self.pq.insert(n) def moves(self): return self.goal.moves if not self.goal is None else -1 def solution(self): stck = Stack() node = self.goal while not node is None: stck.push(node.board) node = node.prev return stck