示例#1
0
def shortest_path(source, target):
    """
    Returns the shortest list of (movie_id, person_id) pairs
    that connect the source to the target.

    If no possible path, returns None.
    """
    frontier = QueueFrontier()
    node = Node(source, None, None)
    frontier.add(node)
    nodes_explored = []
    edges = dict()

    print("Calculating...")
    
    while True:
  
        if frontier.empty():
            graph = Graph(edges, [])
            graph.draw_graph("my_graph.png")
            return None
        
        node = frontier.remove()
        
        node_person_name = people[node.get_person_id()]["name"]
        
        if node.get_person_id() == target:
            path = []
            path_name_labels = [people[source]["name"]]
            
            while node.get_parent() is not None:
                path.append([node.get_movie_id(), node.get_person_id()])
                path_name_labels.append(people[node.get_person_id()]["name"])
                node = node.get_parent()
            
            path.reverse()
            
            graph = Graph(edges, path_name_labels)
            graph.draw_graph("output_graph.png")
            
            return path
        else:
            nodes_explored.append(node.get_person_id())
            
            for movie_id, person_id in neighbors_for_person(node.get_person_id()):
                
                child = Node(person_id, node, movie_id)
                
                child_person_name = people[child.get_person_id()]["name"]
                movie_name = movies[child.get_movie_id()]["title"]
                
                if(node_person_name != child_person_name):
                    edges[(node_person_name, child_person_name)] = movie_name
                
                if not frontier.contains_state(person_id) and person_id not in nodes_explored:
                    frontier.add(child)