Estoy utilizando la búsqueda de profundidad para identificar rutas en un gráfico ponderado dirigido, mientras reviso los nodos que pertenecen a un ciclo, y establezco condiciones de corte basadas en la distancia total recorrida, o se detiene desde el nodo de origen.espacio extra para búsqueda recursiva en profundidad para almacenar rutas
Según tengo entendido, la recursividad no se requiere una estructura de pila explícita de primera búsqueda en profundidad, así que me preguntaba si podría simplificar aún más mi código de abajo de alguna manera hacer sin la pila explícita:
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 +"]");
}
}
Sin embargo , otras implementaciones recursivas sin una estructura de pila explícita generalmente tienen en cuenta nodos ya visitados, coloreándolos en blanco, gris o negro. Entonces, en mi caso, donde se permite volver a visitar, y la ruta necesita ser registrada, ¿es absolutamente necesaria una pila explícita? Gracias por cualquier sugerencia de alternativas más simples.
Gracias eso tiene mucho sentido. Así que, básicamente, el razonamiento es que si se requiere almacenamiento para guardar la ruta para su uso posterior, entonces independientemente de la implementación, se necesita espacio adicional – denchr