0

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);
    }
}
Redz
  • 324
  • 1
  • 4
  • 16
  • 1
    You could just do BFS/DFS from the node. "acyclic graph with N nodes and N-1 edges" if it is connected, that is called a tree. – Quimby Jan 08 '23 at 00:25
  • I cant see how you can improve that, your code seem to be only running once on each node that you need to update - which seem to be the minimum, unless you have addition details (like you are running on the same nodes more than once) which you didnt include in the question – codingStarter Jan 08 '23 at 00:35
  • 1
    @Quimby if it wasn't connected, it would have cycles as it has N nodes and N-1 edges. So it is a tree. – ALX23z Jan 08 '23 at 01:38
  • How long is "once N starts to get bigger than 1000 [...] it becomes too slow"? Also, what does it mean that "[you] also need to make sure that [you] only update each node once"? – Atmo Jan 08 '23 at 04:28
  • I have just seen your edit. Do you mean it takes 4secs to browse through 1000 nodes on each and every call? Or only the first time? – Atmo Jan 08 '23 at 04:58
  • it is a tree - so as long as he doesnt return back on the same edge he arrived from - he wont check any node twice. and he did made that check – codingStarter Jan 08 '23 at 14:01
  • 1
    In addition to `adjList`, set up and maintain a `visitedSet`. Instead of pruning on `next_node == parent_node`, prune on `!visitedSet.emplace(next_node).second`. – Andrej Podzimek Jan 08 '23 at 21:27

0 Answers0