任何人都可以帮助我使用BFS算法,我不知道出了什么问题:
public class Graph {
private final List<City> cities;
private final List<Route> routes;
private final Map<City, List<Route>> myGraph = new HashMap<City,List<Route>>();
public Map<String,City> BFS(Graph graph, City from, City to) {
boolean found = false;
ArrayList<City> visited = new ArrayList<City>();
Queue<City> toVisit = new LinkedList<City>();
Map<String,City> rute = new HashMap<String,City>();
toVisit.add(from);
City node;
while (!toVisit.isEmpty()&&(!found)) {
node = toVisit.remove();
visited.add(node);
if (node.equals(to)) {
rute.put(node.getId(), node);
found = true;
}
else {
List<City> aux = new ArrayList<City>();
List<City> neighbors = new ArrayList<City>();
neighbors = this.getNeighbors(node);
for (City n : neighbors)
aux.add(n);
for (City n : aux)
if (!visited.contains(n)&&(!n.equals(to))) {
rute.put(n.getId(), node); // <--- this
toVisit.add(n);
}
}
}
// for (int j = 0;j<rute.size();j++)
// System.out.println(rute.get(j));
String current = to.getId();
StringBuffer route = new StringBuffer();
route.append(current);
while(current != null) {
if (rute.containsKey(current)) {
current = rute.get(current).getId();
route.insert(0, current +"-->");
} else {
current = null;
}
}
System.out.println(route);
return rute;
}
我需要找到两个城市之间的最短路径。我想保存rute
地图中的所有路线,然后检查哪一条路线的距离最短。问题是算法结束后rute
为空。我无法弄清楚出了什么问题。请帮帮我
答案 0 :(得分:0)
您的问题是访问过的,它是一个城市列表,您确实包含在其中。对于这类事情,Map更快,并且还将确保将String的值作为键进行比较。
在Graph.BFS方法中,用Map替换List中的visit:
Map visited = new HashMap();
然后:
...
while (!toVisit.isEmpty()&&(!found)) {
node = toVisit.remove();
visited.put(node.getId(), true); // <--- this was changed
和
for (City n : aux)
if (!visited.containsKey(n.getId())&&(!n.equals(to))) { // <-- this was changed
答案 1 :(得分:0)
您应该拥有对每个节点的父级的引用。这样,当您找到目的地时,您可以遍历图表。
public class Node {
String id;
Node parent;
ArrayList<Node> children;
}
从目的地集from.parent = null
开始。找到目的地后,通过
StringBuffer path = new StringBuffer(destination.id);
Node current = destination;
while (current.parent != null) {
path.append(current.id);
current = current.parent;
}
这将为您提供两个城市之间最短距离的反向路径。当然,这是假设所有边缘都有统一的成本。