Suppose you have a weighted graph. Starting from a random node, how can you use depth first search (modify the iterative algorithm that uses an explicit stack) to check which nodes exist within a certain weight radius? (Are reachable from this node in a specific weight.)
Share
Suppose we use the type
Nodeto denote a node in the graph. In the simplest case,Nodecould be just an integer (int).Normally, we use an explicit stack of type
Node. In your case, we can use a stack of typepair<Node,int>wherepair<A,B>is the type of a pair, and theintrepresents the distance from your starting point to thisNode.Suppose we are now at
Nodeuwith distanced. For an adjacentNodev, letwbe the weight of the edgeuv. Then just pushpair(v, d+w)to the stack. Initially, pushpair(v0, 0)wherev0is the starting point of the depth first search.