Find all nodes up to distance K from target node

144 Views Asked by At

I have an undirected, acyclic graph with N nodes and N-1 edges. I have a function where I get a node, A. I need to update all nodes which are at distance D or less away from A (for example, if D is 2, I need to update all nodes which can be reached from A in at most 2 edges). As updating a node changes the value of the node, I also need to make sure that I only update each node once.

Currently, I'm doing this with a recursive function and an adjacency list. However, once N starts to get bigger than 1000 (I need to do this function several times) it becomes too slow (since the whole program needs to run in under 4 seconds and there are several calls to update different sets of nodes). Is there a different way to do this?

My current recursive function in C++:

void update(int parent_node, int current_node, int dist) {
    update the node

    if (dist == 0) return;
    dist--;
    for (int next_node : adjList[current_node]) {
        if (next_node == parent_node) continue;
        update(current_node, next_node, dist);
    }
}
0

There are 0 best solutions below