Exemple #1
0
def depth_first_search_recursive(graph, start, goal, parent=None):
    if parent is None:
        parent = {}
    visited = set()
    visited.add(start)
    for vertex, weight in graph.get_neighbors(start):
        if vertex not in visited:
            parent[vertex] = start
            if vertex != goal:
                depth_first_search_recursive(graph, vertex, goal, parent)
    return get_path(goal, parent)
def djikstra_heap(graph, start, goal):
    all_nodes = graph._container.keys()
    distances = {node: float('inf') for node in all_nodes}
    distances[start] = 0
    to_explore = [(distances[start], start)]
    parent = {}
    while to_explore:
        origin_wt, origin = heappop(to_explore)
        for vertex, weight in graph.get_neighbors(origin):
            if distances[vertex] > origin_wt + weight:
                distances[vertex] = origin_wt + weight
                heappush(to_explore, (origin_wt + weight, vertex))
                parent[vertex] = origin

    return get_path(goal, parent)
def bfs(graph, start: str, goal: str):
    visited = []
    parent = {}
    frontier = deque()
    frontier.append(start)
    while frontier:
        check = frontier.popleft()
        visited.append(check)
        for dest, weight in graph.get_neighbors(check):
            if dest not in visited:
                frontier.append(dest)
                parent[dest] = check
            if dest == goal:
                return get_path(goal, parent)
    return False
Exemple #4
0
def depth_first_search_stack(graph, start, goal) -> List[str]:
    frontier = deque()
    visited = set()
    parent = {}
    frontier.append(start)
    while frontier:
        checked_vertex = frontier.pop()
        visited.add(checked_vertex)
        for vertex, weight in graph.get_neighbors(checked_vertex):
            if vertex not in visited:
                frontier.append(vertex)
                parent[vertex] = checked_vertex
            if vertex == goal:
                return get_path(goal, parent)
    return False
def djikstra(graph, start, goal):
    all_nodes = graph._container.keys()
    distances = {node: float('inf') for node in all_nodes}
    distances[start] = 0
    processed = set()
    node = start
    parent = {}
    while all_nodes - processed:
        processed.add(node)  # add node to set 'processed'
        for vertex, weight in graph.get_neighbors(node):
            # check if weight in distances dictionary is larger than this path
            if vertex not in processed:
                if distances[vertex] > distances[node] + weight:
                    distances[vertex] = distances[node] + weight
                    parent[vertex] = node
        if all_nodes - processed:  # gives set of all unprocessed nodes
            # sets variable 'node' to smallest remaining unprocessed node
            node = min([i for i in all_nodes - processed],
                       key=lambda x: distances[x])
    return get_path(goal, parent)