2014-03-28 84 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

相关问题