[英]How to get shortest path between two nodes with Breadth First Search?
I am brushing up my algorithm and data structure knowledge and was wondering if someone could help me figure out how to find the shortest path between two nodes with BFS
.我正在复习我的算法和数据结构知识,想知道是否有人可以帮助我弄清楚如何使用
BFS
找到两个节点之间的最短路径。 So far I am have the following method, which returns the shortest parth in a graph:到目前为止,我有以下方法,它返回图中最短的部分:
private Node[] nodes;
public static int[] shortestPath(Node source){
LinkedList<Node> queue = new LinkedList<Node>();
queue.add(source);
int[] distances = new int[totalNodes];
Arrays.fill(distances,-1);
distances[source] = 0;
while(!queue.isEmpty()){
Node node = queue.poll();
for (int neighbor: nodes[node].neighbor) {
if(distances[neighbor] == -1) {
distances[neighbor] += distances[distanceIndex] + 1;
queue.add(neighbor);
}
}
}
return distances;
}
}
I was wondering how would the solution look if I wanted to implement a method like this:我想知道如果我想实现这样的方法,解决方案会如何:
public static int[] shortestPath(Node source, Node destination){
//
}
Thanks in advance for the help, I am new to data structures and not sure how to go about it提前感谢您的帮助,我是数据结构的新手,不知道如何了解 go
private Node[] nodes;
public static int shortestPath(Node source, Node destination){
LinkedList<Node> queue = new LinkedList<Node>();
queue.add(source);
int[] distances = new int[totalNodes];
Arrays.fill(distances,-1);
distances[source] = 0;
while(!queue.isEmpty()){
Node node = queue.poll();
for (int neighbor: nodes[node].neighbor) {
if(distances[neighbor] == -1) {
distances[neighbor] += distances[node] + 1;
queue.add(neighbor);
if(neighbor == destination)
break;
}
}
}
return distances[destination];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.