2014-03-28 83 views
0

我有一個圖表示爲鄰接矩陣,我想找到兩個節點之間的最短路徑。該圖是加權的。我想使用BFS算法,我嘗試了但我用完了想法。這是我的代碼,如果你能幫助我。找到2個節點之間的最短路徑沒有更多的想法

public class A { 
    private static int[][] adjacency = new int [4][4]; 
    static int n = 4; 

    public static void main(String[] args) { 
     for (int i=0;i<n;i++) 
      for (int j=0;j<n;j++) 
       adjacency[i][j] = 0;  
     adjacency[0][1] = 2; 
     adjacency[0][3] = 1; 
     adjacency[1][0] = 2; 
     adjacency[1][2] = 5; 
     adjacency[2][1] = 5; 
     adjacency[2][3] = 1; 
     adjacency[2][4] = 2; 
     adjacency[3][0] = 1; 
     adjacency[3][2] = 1; 
     adjacency[4][2] = 2; 
    } 

    public List<Integer> getNeighbors(int node, int[][] a) { 
     List<Integer> list = new ArrayList<Integer>(); 
     for(int i=0;i<n;i++) 
      if (a[node][i] != 0) 
       list.add(i); 
     return list; 
    } 

    public List<Queue<Integer>> findPath(int start, int end, int[][] a) { 
     List<Queue<Integer>> paths = new ArrayList<Queue<Integer>>(); 
     Queue<Integer> toVisit = new LinkedList<Integer>(); 
     Queue<Integer> visited = new LinkedList<Integer>(); 
     toVisit.add(start); 
     while(!toVisit.isEmpty()) { 
       int node = toVisit.remove(); 
       visited.add(node); 
       List<Integer> neighbors = new ArrayList<Integer>(); 
       neighbors = this.getNeighbors(node,a); 
     } 
      return paths; 
    } 
} 

所以基本上我在想是要找到所有的2個給出節點之間的路徑,並將其存儲在隊列的列表,然後檢查其路徑具有最短距離。你能幫我麼。

+0

BFS爲等權在所有鏈路的最短路徑算法,都是你的鏈接相同的權重? – Alejandro

+0

http://en.wikipedia.org/wiki/Shortest_path_problem你讀過那裏嗎?我記得Dijkstra和A *非常有效,雖然效率不高。 –

+0

@ RB-Develop,我不認爲他們被認爲是尋找最短路徑的「低效率」。如果你將BFS與Dijkstra/A *進行比較,那麼蘋果就不是蘋果。 – Alejandro

回答

3

有幾種算法可以在你的情況下使用。一個非常普遍的方法是使用Dijkstra算法: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

爲「Dijkstra的最短路徑算法的java」對谷歌會給你幾頁關於如何在Java中實現示例的搜索。

+0

好的答案,我認爲在那裏提及Dijkstra是A *算法的一個特例會很有幫助 – Alejandro

+0

我知道Dijkstra會更好,但我必須使用BFS。它是必需的 – user3421241

+0

@ user3421241 Dijkstra's是一種BFS,A *也是一種BFS。 –

0

Dijkstra算法是非常適合您的問題, 這個網址是Link

相關問題