我通过以下方式在加权有向图上实现 DFS:
public class DFSonWeightedDirectedGraph {
private static final String START = "A";
private static final String END = "C";
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", 5);
graph.addEdge("A", "D", 5);
graph.addEdge("A", "E", 7);
graph.addEdge("B", "C", 4);
graph.addEdge("C", "D", 8);
graph.addEdge("C", "E", 2);
graph.addEdge("D", "C", 8);
graph.addEdge("D", "E", 6);
graph.addEdge("E", "B", 3);
LinkedList<String> visited = new LinkedList<String>();
visited.add(START);
new DFSonWeightedDirectedGraph().depthFirst(graph, visited);
}
private void depthFirst(WeightedDirectedGraph graph, LinkedList<String> visited) {
Collection<Map.Entry<String, Integer>> nodes = graph.adjacentNodes(visited.getLast());
// examine adjacent nodes
for (Map.Entry<String, Integer> node : nodes) {
if (visited.contains(node.getKey())) {
continue;
}
if (node.getKey().equals(END)) {
visited.addLast(node.getKey());
pathLength += node.getValue();
stops += 1;
printPath(visited);
visited.removeLast();
pathLength -= node.getValue();
stops -= 1;
break;
}
}
// recursion
for (Map.Entry<String, Integer> node : nodes) {
if (visited.contains(node.getKey()) || node.getKey().equals(END)) {
continue;
}
visited.addLast(node.getKey());
pathLength += node.getValue();
stops += 1;
depthFirst(graph, visited);
visited.removeLast();
pathLength -= node.getValue();
stops -= 1;
}
}
private void printPath(LinkedList<String> visited) {
for (String node : visited) {
System.out.print(node);
System.out.print(" ");
}
System.out.println("[path length: "+pathLength +
" stops made: "+ stops+"]");
}
}
我需要修改上述内容以允许在搜索源节点和目标节点之间的所有路径期间循环。为避免无限循环,可以设置条件以根据“停止”的数量或从源行进的最大允许距离来终止搜索。
例如,这样我可以找到从 A 开始到 D 结束的行程数,恰好有 5 个停靠点:一种解决方案可以是 ABCDCD。或者,我可以找到从 D 到 D 的距离小于 40 的不同路线的数量:一些解决方案是 DECD、DEBCD、DCDCD。
我的问题是我不确定如何创建保持主算法搜索的逻辑,同时逃避保证不会到达目标节点的无限搜索循环。
假设我想从 A 到 D。一个可能的死循环可能是 ABCEBCEBCEB....(到无穷大)。我基于停靠点数或总行驶距离的条件可以终止此循环,但也将结束整个搜索,否则可能会找到正确的路径 ABCDCDCDCD,当满足任一预设条件时,它将正确终止。
感谢您的任何想法。