我正在使用深度优先搜索来识别有向加权图中的路径,同时重新访问属于循环的节点,并根据行进的总距离或从源节点停止的距离设置截止条件。
据我了解,使用递归,深度优先搜索不需要显式堆栈结构,所以我想知道是否可以通过某种方式不使用显式堆栈来进一步简化下面的代码:
public class DFSonWeightedDirectedGraph {
private static final String START = "A";
private static final String END = "E";
private int pathLength = 0;
private int stops = 0;
public static void main(String[] args) {
//this is a directed weighted graph
WeightedDirectedGraph graph = new WeightedDirectedGraph();
graph.addEdge("A", "B", 15);
graph.addEdge("A", "D", 15);
graph.addEdge("A", "E", 27);
//(...) more edges added
Stack<String> visited = new Stack<String>();
visited.push(START);
new DFSonWeightedDirectedGraph().depthFirst(graph, visited);
}
private void depthFirst(WeightedDirectedGraph graph, Stack<String> visited) {
Collection<Map.Entry<String, Integer>> tree_of_children
= graph.get_tree_of_children(visited.peek());
for (Map.Entry<String, Integer> child : tree_of_children) {
if(pathLength + child.getValue()>= 20){
continue;
}
visited.push(child.getKey());
pathLength += child.getValue();
stops += 1;
if (child.getKey().equals(END)) {
printPath(visited);
}
depthFirst(graph, visited);
visited.pop();
pathLength -= child.getValue();
stops -= 1;
}
}
private void printPath(Stack<String> visited) {
for (String node : visited) {
System.out.print(node);
System.out.print(" ");
}
System.out.println("[path length: "+pathLength +
" stops made: " + stops +"]");
}
}
然而,其他没有显式堆栈结构的递归实现通常会考虑已经访问过的节点,将它们着色为白色、灰色或黑色。那么,在我允许重新访问并且需要记录路径的情况下,绝对需要显式堆栈吗?感谢您对更简单的替代方案的任何建议。