2017-10-16 79 views
0

我試圖修改Dijkstra的算法以顯示所有具有最小值的路徑。所以我決定使用以前的頂點列表。我添加了一個if子句,用於檢查路徑是否爲具有最小值的前一個值,並將前一個頂點添加爲當前父元素的父元素。 問題是我得到一個StackOverflow錯誤,我不知道是什麼導致它。 這是我的代碼: 下面的代碼的目的是爲圖中的所有頂點計算Dijkstra,計算頂點出現在最小路徑中的次數,並按降序顯示它們全部。修改Dijkstra以保存具有相同值的路徑 - StackOverflow錯誤

public class Dijkstra { 

    public static final Map<String, Integer> ordem = new HashMap<>(); 

    public static void main(String[] args) throws FileNotFoundException, IOException { 
     List<Graph.Edge> edges = new ArrayList<>(); 

     try { 
      FileReader arq = new FileReader("input.txt"); 
      BufferedReader fw = new BufferedReader(arq); 
      String linha = ""; 
      while (fw.ready()) { 
       linha = fw.readLine(); 
       if (!linha.equals("0,0,0")) { 
        String parts[] = linha.split(","); 
        ordem.put(parts[0], 0); 
        ordem.put(parts[1], 0); 
        Graph.Edge a = new Graph.Edge(parts[0], parts[1], 100 - Integer.parseInt(parts[2])); 
        edges.add(a); 
       } else { 
        break; 
       } 

      } 
      fw.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
     Graph g = new Graph(edges); 

     for (int i = 0; i < 5; i++) { 
      g.dijkstra(String.valueOf(i)); 
      g.printAllPaths(); 
     } 

     Object[] a = ordem.entrySet().toArray(); 
     Arrays.sort(a, new Comparator() { 
      public int compare(Object o1, Object o2) { 
       return ((Map.Entry<String, Integer>) o2).getValue() 
         .compareTo(((Map.Entry<String, Integer>) o1).getValue()); 
      } 
     }); 
     for (Object e : a) { 
      System.out.print(((Map.Entry<String, Integer>) e).getKey() + " "); 
     } 
     System.out.println("\n"); 
    } 
} 

class Graph { 

    private final Map<String, Vertex> graph; 

    public static class Edge { 

     public final String v1, v2; 
     public final int dist; 

     public Edge(String v1, String v2, int dist) { 
      this.v1 = v1; 
      this.v2 = v2; 
      this.dist = dist; 
     } 
    } 

    public static class Vertex implements Comparable<Vertex> { 

     public final String name; 
     public int dist = Integer.MAX_VALUE; 
     public List<Vertex> previous = new ArrayList<>(); 
     public final Map<Vertex, Integer> neighbours = new HashMap<>(); 

     public Vertex(String name) { 
      this.name = name; 
     } 

     private void printPath() { 
      if (this == this.previous) { 
      } else if (this.previous == null) { 
      } else { 
       //This is where I am getting the error 
       for (int i = 0; i<this.previous.size(); i++){ 
       this.previous.get(i).printPath(); 
       Dijkstra.ordem.replace(this.name, Dijkstra.ordem.get(this.name) + 1); 
      } 

      } 
     } 

     public int compareTo(Vertex other) { 
      if (dist == other.dist) { 
       return name.compareTo(other.name); 
      } 

      return Integer.compare(dist, other.dist); 
     } 

     @Override 
     public String toString() { 
      return "(" + name + ", " + dist + ")"; 
     } 
    } 

    public Graph(List<Graph.Edge> edges) { 
     graph = new HashMap<>(edges.size()); 

     for (Edge e : edges) { 
      if (!graph.containsKey(e.v1)) { 
       graph.put(e.v1, new Vertex(e.v1)); 
      } 
      if (!graph.containsKey(e.v2)) { 
       graph.put(e.v2, new Vertex(e.v2)); 
      } 
     } 

     for (Edge e : edges) { 
      graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); 
      graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); 
     } 
    } 


    public void dijkstra(String startName) { 
     if (!graph.containsKey(startName)) { 
      System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName); 
      return; 
     } 
     final Vertex source = graph.get(startName); 
     NavigableSet<Vertex> q = new TreeSet<>(); 

     // Inicializacao dos vertices 
     for (Vertex v : graph.values()) { 
      //v.previous = v == source ? list : null; 
      if (v == source) { 
       v.previous.add(source); 
      } else { 
       v.previous = new ArrayList<>(); 
      } 
      v.dist = v == source ? 0 : Integer.MAX_VALUE; 
      q.add(v); 
     } 

     dijkstra(q); 
    } 

    private void dijkstra(final NavigableSet<Vertex> q) { 
     Vertex u, v; 
     while (!q.isEmpty()) { 

      u = q.pollFirst(); 
      if (u.dist == Integer.MAX_VALUE) { 
      } 
      for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) { 
       v = a.getKey(); 

       final int alternateDist = u.dist + a.getValue(); 
       if (alternateDist < v.dist) { 
        q.remove(v); 
        v.dist = alternateDist; 
        v.previous.add(u); 
        q.add(v); 
       } else if(alternateDist == v.dist) { 
        v.previous.add(u); 
       } 
      } 
     } 
    } 


    public void printPath(String endName) { 
     if (!graph.containsKey(endName)) { 
      System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName); 
      return; 
     } 

     graph.get(endName).printPath(); 
     //System.out.println(); 
    } 

    public void printAllPaths() { 
     for (Vertex v : graph.values()) { 
      v.printPath(); 
     } 
    } 
} 

這是錯誤:

Exception in thread "main" java.lang.StackOverflowError 
    at Graph$Vertex.printPath(Dijkstra.java:117) 
    at Graph$Vertex.printPath(Dijkstra.java:118) 
+0

哇,這是很多代碼。你真的期望有人拖網槽? ''StackOverflowException'通常發生在你有一些無限遞歸時。簡單地說:void a(){a(); }'。 –

+0

當你在一個小的網格(比如3x3或4x4)網格中找到路徑時,你還能得到它嗎?在這個尺度上,可能會輸出每一步,並通過這樣做來檢測算法的錯誤。 – GolezTrol

+0

感謝您的回覆!我剛剛在for循環中添加了一條註釋,讓我得到這個錯誤。 @GolezTrol我正在用5個頂點和5個邊測試圖中的代碼。 –

回答

0

作爲錯誤信息已經暗示:你Dijkstra算法不是問題。 問題是printPath()調用自己。

有可能的罪魁禍首是

if (this == this.previous) {} ... 

你比較Vertex thisList<Vertex> previous。也許你想檢查

if (this == this.previous.get(this.previous.size() - 1)) {} ... 

改爲。我沒有測試這個,因爲你的代碼是(1)太長了,(2)沒有自包含(至少缺少「input.txt」)。

+0

感謝您的回覆! input.txt中會是這樣的: 0,1,70 1,2,50 2,3,88 3,4,20 4,2,5 0,0,0 每一行都是一個邊(第一個和第二個屬性是頂點,第三個是邊的權重,每個邊必須在文件的不同行中)。我會嘗試你的建議。 –