Я пытаюсь найти путь между двумя узлами (sourcenode и targetnode). я придумал этот код, но я не могу заставить его рекурсивно найти путь. Я даже устанавливаю узлы в null, если целевой узел найден, но я продолжаю получать ошибку переполнения стека.Graph path finder
public void findPathBetween(Node sourceNode, Node targetNode){
//find a path between the sourceNode and targetNode
//select the nodes and edges along the path if one exists.
ArrayList<Node> nodesToSearch = new ArrayList<Node>();
nodesToSearch.add(sourceNode);
//basis
if(sourceNode == null || targetNode == null) return;
//recursion
ArrayList<Node> newNodesToSearch = new ArrayList<Node>(); //get nodes for next level to search
for(Node aNode : nodesToSearch) {
for (Node neighbour : aNode.getNeighbours()) {
if (neighbour != targetNode && newNodesToSearch.isEmpty()) {
newNodesToSearch.add(neighbour);
neighbour.setSelected(true);
edgeBetween(aNode, neighbour).setSelected(true);
sourceNode = neighbour;
}
if (neighbour == targetNode) {
sourceNode = null;
targetNode = null;
return;
}
}
}
if(sourceNode != null &&targetNode != null) {
findPathBetween(sourceNode, targetNode);
}
}