// get all the nodes that are within Range distance of the root node of graph Set<int> GetNodesInRange(Graph graph, int Range) { Set<int> out = new Set<int>(); GetNodesInRange(graph.root, int Range, out); return out; } // get all the nodes that are within Range successor distance of node // accepted nodes are placed in out void GetNodesInRange(Node node, int Range, Set<int> out) { boolean alreadyVisited = out.add(node.value); if (alreadyVisited) return; if (Range == 0) return; // for each successor node { GetNodesInRange(successor, Range-1, out); } } // get all the nodes that are within Range distance of selected node in graph Set<int> GetNodesInRange(Graph graph, int Range, int selected) { Set<int> out = new Set<int>(); GetNodesInRange(graph, Range, selected, out); return out; } // get all the nodes that are successors of node and within Range distance // of selected node // accepted nodes are placed in out // returns distance to selected node int GetNodesInRange(Node node, int Range, int selected, Set<int> out) { if (node.value == selected) { GetNodesInRange(node, Range-1, out); return 1; } else { int shortestDistance = Range + 1; // for each successor node { int distance = GetNodesInRange(successor, Range, selected, out); if (distance < shortestDistance) shortestDistance = distance; } if (shortestDistance <= Range) { out.add(node.value); } return shortestDistance + 1; } }
I changed your requirements a bit to return Set , not List .
The GetNodesInRange(Graph, int, int) method will not process graphs containing loops. This can be overcome by maintaining a collection of nodes that have already been visited. The GetNodesInRange(Graph, int) method GetNodesInRange(Graph, int) advantage of the fact that the out set is the set of visited nodes to overcome cycles.
Note. This has not been tested in any way.
Matthew T. Staebler
source share