Can anyone help me with the BFS algorithm, I don't know what is wrong :
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;
}
I need to find the shortest path between 2 cities. I would like to save all the routes in the rute
map and then just check which one has the shortest distance. The problem is that after the algorithm ends rute
is empty. I can't figure it out what is wrong. Please help me