我正在尝试创建一个程序,可以添加节点并使用LinkedList将它们连接起来。一旦这些节点被连接起来,我想使用Breadth First Search找到它们之间的最短路径。目前我的程序只能找到是否有路径,但我想知道这条路径是什么。我该如何修改代码?
public static boolean findPath(String start, String destination){
//find the nodes given the String key
Node current = getNode(start);
Node end = getNode(destination);
//create a linked list to store the visited nodes
LinkedList<Node> nextToVisit = new LinkedList<Node>();
HashSet<Node> visited= new HashSet<Node>();
nextToVisit.add(current);
while(!nextToVisit.isEmpty()){
Node node = nextToVisit.remove();
System.out.println(node.name);
if(node == end)
return true;
if(visited.contains(node))
continue;
visited.add(node);
for(Node children : node.adjacent){
nextToVisit.add(children);
}
}
return false;
}
LinkedList
而非Queue
来进行 BFS。Linkedlist.remove()
将移除链表头部。 - XPLOT1ON