重み付けされていないグラフで、あるノードから別のノードへの最短経路を返すメソッドを作成しようとしています。ダイクストラ法の使用を検討しましたが、ペアが1つしかないので、これは少しやり過ぎのようです。代わりに幅優先探索を実装しましたが、問題は、返されるリストに不要なノードが含まれていることです。目標を達成するためにコードを変更するにはどうすればよいですか?
public List<Node> getDirections(Node start, Node finish){
List<Node> directions = new LinkedList<Node>();
Queue<Node> q = new LinkedList<Node>();
Node current = start;
q.add(current);
while(!q.isEmpty()){
current = q.remove();
directions.add(current);
if (current.equals(finish)){
break;
}else{
for(Node node : current.getOutNodes()){
if(!q.contains(node)){
q.add(node);
}
}
}
}
if (!current.equals(finish)){
System.out.println("can't reach destination");
}
return directions;
}