簡體   English   中英

我的廣度優先搜索算法不起作用

[英]My Breadth-First-Search algorithm not working

誰能幫助我使用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為空。 我不知道這是什么問題。 請幫我

您的問題是訪問者,它是城市列表,您確實包含其中。 Map在這種情況下速度更快,並且還將確保將String的值作為鍵進行比較。

在Graph.BFS方法中,用Map替換從List訪問的列表:

已訪問的地圖=新的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

您應該保留對每個節點的父節點的引用。 這樣,您可以在找到目的地時遍歷圖。

 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;
}

這將為您提供兩個城市之間最短距離的反向路徑。 當然,這是假設您的所有優勢都費用統一的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM