Harvard CS50 Project0:Degrees

哈佛大学公开课CS50 Introduction to Artificial Intelligence with Python的Project0第1题Degrees的参考解答,用BFS找到了莱坞明星人物关系通过共同作品产生联系的最短距离。

def shortest_path(source, target):
    """
    Returns the shortest list of (movie_id, person_id) pairs
    that connect the source to the target.
    source and target are string format of person_id
    If no possible path, returns None.
    """

    start = Node(state = source, parent = None, action = None)
    frontier = QueueFrontier()
    frontier.add(start)

    num_explored = 0
    explored = set()

    while True:
        if frontier.empty():
            raise Exception("no solution")

        node = frontier.remove()
        num_explored += 1

        if node.state == target:
            actions = []
            cells = []
            while node.parent is not None:
                actions.append(node.action)
                cells.append(node.state)
                node = node.parent
            actions.reverse()
            cells.reverse()
            solution = list(zip(actions,cells))
            return solution
        neighbors = neighbors_for_person(node.state)
        explored.add(node.state)
        for action,state in neighbors:
            if not frontier.contains_state(state) and state not in explored:
                child = Node(state=state,parent=node,action=action)
                frontier.add(child)

运行结果如下:
Harvard CS50 Project0:Degrees_第1张图片

Harvard CS50 Project0:Degrees_第2张图片

你可能感兴趣的:(#,python习题)