我使用深度優先搜索來識別有向加權圖中的路徑,同時重新訪問屬於一個循環的節點,並根據總行進距離設置截斷條件,或者從源節點停止。用於遞歸深度優先搜索以存儲路徑的額外空間
據我瞭解,遞歸明確的堆疊結構不需要深度優先搜索,所以我在想,如果我可以進一步通過某種方式做不明確的堆棧下方簡化我的代碼:
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 +"]");
}
}
然而,沒有明確堆棧結構的其他遞歸實現通常會考慮已訪問節點,將它們着色爲白色,灰色或黑色。那麼,在我的情況下,允許重新訪問,並且需要記錄路徑,是絕對需要的顯式堆棧?感謝您提供更簡單替代方案的任何建議。
謝謝,這很有意義。所以基本上推理是,如果需要存儲器來保存路徑以供進一步使用,那麼無論實現多餘空間都是必需的 – denchr 2010-01-09 13:37:40