简体   繁体   中英

My Breadth-First-Search algorithm not working

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

Your problem is the visited, it is a List of Cities and you do contains in it. A Map is faster for this kind of things, and also will ensure to compare the value of the String as key.

In the Graph.BFS method replace the visited from a List by a Map:

Map visited = new HashMap();

And then:

...
while (!toVisit.isEmpty()&&(!found)) {
          node = toVisit.remove();
          visited.put(node.getId(), true); // <--- this was changed

and:

for (City n : aux)
                  if (!visited.containsKey(n.getId())&&(!n.equals(to))) {  // <-- this was changed

You should hold a reference to each node's parent. That way you can traverse back up the Graph when you find your destination.

 public class Node {
   String id;
   Node parent;
   ArrayList<Node> children;
 }

When you start at your from destination set from.parent = null . When you find your destination, traverse back via

StringBuffer path = new StringBuffer(destination.id);
Node current = destination;
while (current.parent != null) {
   path.append(current.id);
   current = current.parent;
}

This will give you the reverse path of the shortest distance between two cities. This is, of course, assuming that all of your edges have uniform costs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM