广度优先搜索的时间复杂度与节点总数有关,如果是满二叉树,最后一层的节点数是个,其中b为brantching,h为hight。节点总数为 ,因此时间复杂度是。
而空间复杂度,设想最坏的一种情况,这个queue需要存放所有节点,所以空间复杂度是。
Illustration:
To do so:
We add the colors to the nodes to have a nice visualisation when displaying. So, these are the different colors we are using in these visuals:
- Un-explored nodes - white
- Frontier nodes (邻接节点) - orange
- Currently exploring node - red
- Already explored nodes - gray
romania_problem = GraphProblem('Arad', 'Bucharest', romania_map)
def tree_breadth_search_for_vis(problem):
"""Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
Don't worry about repeated paths to a state. [Figure 3.7]"""
# we use these two variables at the time of visualisations
iterations = 0
all_node_colors = []
node_colors = {k : 'white' for k in problem.graph.nodes()}
#Adding first node to the queue
#用deque表示队列。O(1)
frontier = deque([Node(problem.initial)])
node_colors[Node(problem.initial).state] = "orange"
iterations += 1
all_node_colors.append(dict(node_colors))
while frontier:
#Popping first node of queue
node = frontier.popleft()
# modify the currently searching node to red
node_colors[node.state] = "red"
iterations += 1
all_node_colors.append(dict(node_colors))
if problem.goal_test(node.state):
# modify goal node to green after reaching the goal
node_colors[node.state] = "green"
iterations += 1
all_node_colors.append(dict(node_colors))
return(iterations, all_node_colors, node)
frontier.extend(node.expand(problem))
for n in node.expand(problem):
node_colors[n.state] = "orange"
iterations += 1
all_node_colors.append(dict(node_colors))
# modify the color of explored nodes to gray
node_colors[node.state] = "gray"
iterations += 1
all_node_colors.append(dict(node_colors))
return None
def breadth_first_tree_search(problem):
"Search the shallowest nodes in the search tree first."
iterations, all_node_colors, node = tree_breadth_search_for_vis(problem)
return(iterations, all_node_colors, node)
all_node_colors = []
romania_problem = GraphProblem('Arad', 'Bucharest', romania_map)
display_visual(romania_graph_data, user_input=False,
algorithm=breadth_first_search_graph,
problem=romania_problem)