Exemplo n.º 1
0
def bfs(road_network, s_vid, e_vid):
    """
    Return the path from vertex s_vid to vertex e_vid using Dijkstra's algorithm.

    The implementation is the same as the function is_reachable(), except that instead of bool type, we return a Path
    found by Breadth First Search.

    :param road_network: RoadNetwork
    :param s_vid: int
    :param e_vid: int
    :return: Path
    """
    frontier = Queue()
    frontier.put(s_vid)
    came_from = dict()
    came_from[s_vid] = None

    while not frontier.empty():
        current = frontier.get()
        if current == e_vid:
            break
        for neighbor in road_network.get_neighbors(current):
            if neighbor not in came_from:
                frontier.put(neighbor)
                came_from[neighbor] = current
    return construct_path(road_network, s_vid, e_vid, came_from)
Exemplo n.º 2
0
def is_reachable(road_network, s_vid, e_vid):
    """
    Return True if there exist a path from s_vid to e_vid, otherwise return False.

    The algorithm is basic Breadth-First-Search (with early exit).

    :param road_network: RoadNetwork
    :param s_vid: int
    :param e_vid: int
    :return: bool
    """
    frontier = Queue()
    frontier.put(s_vid)
    came_from = dict()
    came_from[s_vid] = None

    while not frontier.empty():
        current = frontier.get()
        if current == e_vid:
            return True
        for neighbor in road_network.get_neighbors(current):
            if neighbor not in came_from:
                frontier.put(neighbor)
                came_from[neighbor] = current
    return False