Пример #1
0
def GFS(graph: Graph, starting_node_id, target_id, callback, steps_counter):
    _adjacency_dict = graph.get_adjacency_dict()
    visited_nodes = list()
    next = starting_node_id
    backtrack_index = -1
    while next != target_id:
        steps_counter()  # for each node traversal count the steps
        children = list()  # TODO make it an actual list from the 2 conditions
        if next != None:  # if it's not stuck
            callback(graph.nodes[next])
            visited_nodes.append(next)
            children = [x[0] for x in _adjacency_dict[next]]
        else:  # if it is stuck
            backtrack_index = -2
            # start from the second to last one (the before the stuck)
            current = visited_nodes[backtrack_index]
            visited_nodes.append(visited_nodes[backtrack_index])
            while not has_unvisited_child(_adjacency_dict, current,
                                          visited_nodes):
                # callback(graph.nodes[current])
                backtrack_index -= 2
                current = visited_nodes[backtrack_index]
                visited_nodes.append(visited_nodes[backtrack_index])
                callback(graph.nodes[visited_nodes[backtrack_index]])
            callback(graph.nodes[current])
            children = [x[0] for x in _adjacency_dict[current]]
        next = get_the_closet_to_target_child(graph, children, target_id,
                                              visited_nodes)
    callback(graph.nodes[target_id])
Пример #2
0
def BFS(graph: Graph, starting_node_id, callback, steps_counter):
    """
    Do a BFS over a graph
    NOTE: callback is a function that gets called after each node being visited
    NOTE: callback is expected to take a Node object only as an argument
    """
    visited_nodes = set()
    adjacency_dict = graph.get_adjacency_dict()
    nodes_queue = [starting_node_id]
    while len(nodes_queue):
        node = nodes_queue.pop(0)  # remove the first element, FIFO
        if node not in visited_nodes:
            visited_nodes.add(node)
            connections = adjacency_dict.get(node)
            nodes_list = [node]
            nodes_list.extend(connections)
            callback(nodes_list)
            steps_counter()
            if connections:
                for connection in connections:
                    # add the to index to nodes queue
                    nodes_queue.append(connection[0])
Пример #3
0
def DFS(graph: Graph, starting_node_id):
    """ Do a DFS over a graph """
    target_node_ids = [node.id for node in graph.nodes if node.is_target()]
    adjacency_dict = graph.get_adjacency_dict()
    return lazyDFS_many(starting_node_id, target_node_ids, adjacency_dict)