2012-12-02 73 views
-1

我正在嘗試使用給定鄰接矩陣的優先級隊列實現Dijkstra算法。 我知道問題可能發生在我將頂點添加到優先級隊列的位置,但我無法弄清楚如何修復它!Dijkstra算法與Adjaceny矩陣

static int dijkstra(int[][] g, int i, int j) { 
    // Get the number of vertices in G 
    int n = g.length; 
    int counter = 0; 

    PriorityQueue<Vertex> q = new PriorityQueue<Vertex>(n, new Comparator<Vertex>() {  
     public int compare(Vertex a, Vertex b) { 
      Vertex v1 = (Vertex) a; 
      Vertex v2 = (Vertex) b; 
      if (v1.getD() > v2.getD()) { 
       return 1; 
      } else if (v1.getD() < v2.getD()) { 
       return -1; 
      } else { 
       return 0; 
      } 
     } 
    }); 
    int[] distance = new int[n]; 
    for (int l = 0; l < n; l++) { 
     distance[l] = 99999; 
    } 
    distance[i] = 0; 

    for (int l = 0; l < n/2; l++) { 
     for (int m = 0; m < n; m++) { 
      if (g[l][m] > 1) { 
       System.out.printf("%d was added \n", g[l][m]); 
       q.add(new Vertex(l, g[l][m])); 
      } 
     } 
    } 
    while (!q.isEmpty()) { 
     int u = 0; 
     for (int z = 0; z < n; z++) { 
      if (distance[z] < distance[u]) { 
       u = z; 
      } 
     } 
     if (distance[u] == 99999) { break; } 
     q.remove(); 
     for (int l = 0; l < n; l++) { 
      if (g[u][l] > 1) { 
       int alt = distance[u] + g[u][l]; 
       if (alt < distance[l]) { 
        distance[l] = alt; 
        q.remove(); 
        q.add(new Vertex(u, distance[l])); 
       } 
      } 
     } 
    } 

    for (int k = 0; k < n; k++) { 
     System.out.printf("==>%d", distance[j]); 
    } 
    return distance[j]; 
} 

和:

class Vertex { 
    int v,d; 
    public Vertex(int num, int dis) { 
     v = num; 
     d = dis; 
    } 
    public int getV() { 
     return v; 
    } 
    public int getD() { 
     return d; 
    } 
} 

我用下面的矩陣測試:

0 0 0 0 0 0 0 38 0 0 0 0 0 0 0 0 
0 0 0 0 65 0 64 0 6 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 6 8 0 0 0 62 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 65 0 0 0 0 0 0 0 6 0 0 0 0 55 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 64 0 0 0 0 0 53 0 0 36 0 45 0 0 0 
38 0 0 0 0 0 53 0 0 0 0 91 0 29 0 0 
0 6 0 0 0 0 0 0 0 0 0 95 55 0 0 0 
0 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 
0 0 6 0 0 0 36 0 0 0 0 0 0 0 0 0 
0 0 8 0 0 0 0 91 95 0 0 0 60 0 0 0 
0 0 0 0 0 0 45 0 55 0 0 60 0 0 0 0 
0 0 0 0 0 0 0 29 0 0 0 0 0 0 0 0 
0 0 0 0 55 0 0 0 0 0 0 0 0 0 0 0 
0 0 62 0 0 0 0 0 0 0 0 0 0 0 0 0 

並開始爲0,到底是n - 1。我應該得到195,但它似乎沒有任何距離正在改變!

+3

[你有什麼試過?](http://whathaveyoutried.com) –

回答

1

在打印距離時,您始終打印陣列j,而k是迭代器。距離似乎不變,但它們正在改變。

for (int k = 0; k < n; k++) { 
    System.out.printf("==>%d", distance[k]); 
} 

另外,在你的算法中,你將刪除頂部頂點兩次,這是不合理的。該算法應該是這樣的代替:

while (!q.isEmpty()) { 
    int u = q.peek().v; 
    q.remove(); 
    for (int l = 0; l < n; l++) { 
     if (g[u][l] > 1) { 
      int alt = distance[u] + g[u][l]; 
      if (alt < distance[l]) { 
       distance[l] = alt; 
       q.add(new Vertex(u, distance[l])); 
      } 
     } 
    } 
}