def uniformCostSearch(problem):
loc_pqueue = PriorityQueue()
visited_node = {}
parent_child_map = {}
direction_list = []
path_cost = 0
start_node = problem.getStartState()
parent_child_map[start_node] = []
loc_pqueue.push(start_node,path_cost)
def traverse_path(parent_node):
while True:
map_row = parent_child_map[parent_node]
if (len(map_row) == 3):
parent_node = map_row[0]
direction = map_row[1]
direction_list.append(direction)
else:
break
return direction_list
while (loc_pqueue.isEmpty() == False):
parent_node = loc_pqueue.pop()
if (parent_node != problem.getStartState()):
path_cost = parent_child_map[parent_node][2]
if (problem.isGoalState(parent_node)):
pathlist = traverse_path(parent_node)
pathlist.reverse()
return pathlist
elif (visited_node.has_key(parent_node) == False):
visited_node[parent_node] = []
sucessor_list = problem.getSuccessors(parent_node)
no_of_child = len(sucessor_list)
if (no_of_child > 0):
temp = 0
while (temp < no_of_child):
child_nodes = sucessor_list[temp]
child_state = child_nodes[0];
child_action = child_nodes[1];
child_cost = child_nodes[2];
gvalue = path_cost + child_cost
if (visited_node.has_key(child_state) == False):
loc_pqueue.push(child_state,gvalue)
if (parent_child_map.has_key(child_state) == False):
parent_child_map[child_state] = [parent_node,child_action,gvalue]
else:
if (child_state != start_node):
stored_cost = parent_child_map[child_state][2]
if (stored_cost > gvalue):
parent_child_map[child_state] = [parent_node,child_action,gvalue]
temp = temp + 1
评论列表
文章目录