Esempio n. 1
0
def breadthFirstSearch(problem, verbose=False):
	""" Perform a Breadth-First search on the given problem and return a solution.
		NOTE: This is a graph based implementation of the algorithm, please be aware of the memory overhead."""
	start = Node(problem, state = problem.initialState())
	solution = Solution(verbose)

	if problem.goalTest(start.state()): return solution.setGoalNode(start)
	frontier = Queue(items=[start])
	explored = set()
	
	while True:
		solution.trackProgress(frontier, explored)
		if frontier.isEmpty(): raise NoSolutionFoundError()
		node = frontier.dequeue()
		explored.add(node.state())
		for action in problem.applicableActions(node.state()):
			child = Node(problem, node, action)
			if child not in frontier and child.state() not in explored:
				if problem.goalTest(child.state()): return solution.setGoalNode(child)
				else: frontier.enqueue(child)